Skip to content

How do I go about creating a javascript object that stores the count of unique objects?

Lets say I have an array

['Student', 'Progress', 'Student', 'Area']

I would like to have an object that looks like this…

 {
    {
      value: "Student",
      count: 2
    },
    {
      value: "Progress",
      count: 1
    }
 }

The code I am using currently is this… which clearly is wrong. Any help would be appreciated.

    const counts = [];
    for (let i = 0; i < array.length; i++) {
        var object = {
                value: counts[array[i]],
                count: (1 + (counts[array[i]] || 0))
        }
        counts.push(object);
    };
    return counts;

Answer

You could take an object for counting and map the entries of the object as new object.

const
    data = ['Student', 'Progress', 'Student', 'Area'],
    result = Object
        .entries(data.reduce((r, s) => {
            r[s] = (r[s] || 0) + 1;
            return r;
        }, {}))
        .map(([value, count]) => ({ value, count }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }