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

I have an array as follows,

var arr = ['ab','pq','mn','ab','mn','ab']

Expected result

arr['ab'] = 3
arr['pq'] = 1
arr['mn'] = 2

Tried as follows,

$.each(arr, function (index, value) {
    if (value) 
        arr[value] = (resultSummary[value]) ? arr[value] + 1 : 1;
});

console.log(arr.join(','));

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


I think this is the simplest way how to count occurrences with same value in array.

var a = [true, false, false, false];
a.filter(function(value){
    return value === false;
}).length