Skip to content Skip to sidebar Skip to footer

Counting Elements In An Array And Adding Them Into An Object

Okay I researched this one and couldn't find an answer here so hopefully this isn't a duplicate. I'm also trying not to be specific in order to figure this out on my own. var arr =

Solution 1:

You could just reduce the array, and count the keys as you go

var arr = ['cat', 'car', 'cat', 'dog', 'car', 'dog', 'horse'];

function orgNums(input) {
    return input.reduce((a, b) => {
      return b in a ? a[b]++ : a[b] = 1, a;
    }, {});
}

console.log(orgNums(arr));

Solution 2:

The assignment of count, which is used in the loop, does not work in this case, because of the postfix increment count++. This gives you the value of the counter and increment later, If you take the prefix increment ++count, you get the incremented value assigned.

// Postfix 
var x = 3;
y = x++; // y = 3, x = 4

// Prefix
var a = 2;
b = ++a; // a = 3, b = 3

But you can omit the variable and count directly with a property of the object. for all items in one loop.

You could use the element as key for the object. Then assign with zero, if not exist and increment.

var arr = ['cat', 'car', 'cat', 'dog', 'car', 'dog']

function orgNums(input) {
    var obj = {};

    for (var i = 0; i < input.length; i++) {
        obj[input[i]] = obj[input[i]] || 0;
        obj[input[i]]++;
    }
    return obj;
}

console.log(orgNums(arr));

A more compact version of the above with Array#forEach

var arr = ['cat', 'car', 'cat', 'dog', 'car', 'dog']

function orgNums(input) {
    var obj = {};

    input.forEach(function (item) {
        obj[item] = (obj[item] || 0) + 1;
    });
    return obj;
}

console.log(orgNums(arr));

Post a Comment for "Counting Elements In An Array And Adding Them Into An Object"