28

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(','));
Cœur
  • 37,241
  • 25
  • 195
  • 267
Aadi
  • 6,959
  • 28
  • 100
  • 145

9 Answers9

58

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

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
6

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                                      
5

if you don't want a solution that requires a library, and don't have to support legacy javascript:

var report = {};

arr.forEach(function(el){
  report[el] = report[el] + 1 || 1;
});

Or if you want to do it using jQuery:

var report = {};

$.each(arr,function(i,el){
  report[el] = report[el] + 1 || 1;
});

This uses short-circuit logic to test for conditions and set values. I think it's a pretty concise and readable way to do javascript.

console.log( report );
code_monk
  • 9,451
  • 2
  • 42
  • 41
2

Try $.grep

Example:

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

jQuery.grep(arr, function(a){
   return a == 'ab'
}).length // 3

if supporting ie8 is not necessary.

['ab','pq','mn','ab','mn','ab'].filter(function(value){
    return value == 'ab'
}).length // 3
Jackwin tung
  • 319
  • 4
  • 9
1
var result = {};
function count(input){
  var tmp = 0;
  if(result.hasOwnProperty(input)){
     tmp = result[input];
     result[input]=tmp+1;
  }else{
    result[input]=1;
  }
}

above function will help you to count the num of the same string in an Array.

meadlai
  • 895
  • 1
  • 9
  • 22
1

If you are using the Sugar library it's just:

arr.count('ab');

DEMO

See: Array count API.

rsp
  • 107,747
  • 29
  • 201
  • 177
0

Could this be what you are trying to do?

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

this code will count the occurrences of each string in the array and store the results in resultsArray

codebox
  • 19,927
  • 9
  • 63
  • 81
0

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



function getCount(arr,val)
{
    var ob={};
    var len=arr.length;
    for(var k=0;k<len;k++)
    {
        if(ob.hasOwnProperty(arr[k]))
        {
            ob[arr[k]]++;
            continue;
        }
        ob[arr[k]]=1;
    }
    return ob[val];
}



//run test
alert(getCount(arr,'ab'));//3

Demo :http://jsfiddle.net/dmx4y/2/

spaceman12
  • 1,039
  • 11
  • 18
0
var arr = ['ab','pq','mn','ab','mn','ab'];
var result = { };
   for(i=0;i<arr.length;++i) 
   {
       if(!result[arr[i]])
           result[arr[i]]=0;
       ++result[arr[i]];
   }

for (var i in result){
console.log(i+":"+result[i]);
} 
Prashant_M
  • 2,868
  • 1
  • 31
  • 24