How to count the number of occurrences of each item in an array? [duplicate]

no need to use jQuery for this task — this example will build an object with the amount of occurencies of every different element in the array in O(n)

var occurrences = { };
for (var i = 0, j = arr.length; i < j; i++) {
   occurrences[arr[i]] = (occurrences[arr[i]] || 0) + 1;
}

console.log(occurrences);        // {ab: 3, pq: 1, mn: 2}
console.log(occurrences['mn']);  // 2

Example fiddle


You could also use Array.reduce to obtain the same result and avoid a for-loop

var occurrences = arr.reduce(function(obj, item) {
  obj[item] = (obj[item] || 0) + 1;
  return obj;
}, {});

console.log(occurrences);        // {ab: 3, pq: 1, mn: 2}
console.log(occurrences['mn']);  // 2

Example fiddle

Leave a Comment