5

Possible Duplicate:
How to count Matching values in Array of Javascript

I have array with elements as,

array_elements = ["2","1","2","2","3","4","3","3","3","5"];

i want to count array elements like following manner,

Answer:

2 comes --> 3 times
1 comes --> 1 times
3 comes --> 4 times
4 comes --> 1 times
5 comes --> 1 times

Note : Each value count should print only once.

Community
  • 1
  • 1
suresh gopal
  • 3,138
  • 6
  • 27
  • 58
  • You want them counted in Ruby or JavaScipt? If the latter, why ruby tags? – raina77ow Oct 05 '12 at 15:16
  • Do you know how to write a for loop and use an object. Seems like basic homework 101 type of question. – epascarello Oct 05 '12 at 15:20
  • 1
    duplicate questions: http://stackoverflow.com/questions/840781/easiest-way-to-find-duplicate-values-in-a-javascript-array and http://stackoverflow.com/questions/2228362/how-to-count-matching-values-in-array-of-javascript – SDC Oct 05 '12 at 15:23
  • 1
    for people who like fancy words, this is a [histogram](http://en.wikipedia.org/wiki/Histogram) – jbabey Oct 05 '12 at 15:23

4 Answers4

21
var counts = {};

for (var i = 0; i < array.length; i++)
    counts[array[i]] = (counts[array[i]] + 1) || 1;


console.log(counts);

This assumes a toString representation of the items in the Array will be acceptable. For example, it will see 1 as being the same as "1".

Given your example Array, this will not be an issue.

I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
11

You can sort the elements and loop through them:

array_elements = ["2", "1", "2", "2", "3", "4", "3", "3", "3", "5"];

array_elements.sort();

var current = null;
var cnt = 0;
for (var i = 0; i < array_elements.length; i++) {
    if (array_elements[i] != current) {
        if (cnt > 0) {
            document.write(current + ' comes --> ' + cnt + ' times<br>');
        }
        current = array_elements[i];
        cnt = 1;
    } else {
        cnt++;
    }
}
if (cnt > 0) {
    document.write(current + ' comes --> ' + cnt + ' times');
}

Demo: http://jsfiddle.net/Guffa/aQsuP/

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
5
var array_elements = ["2","1","2","2","3","4","3","3","3","5"];

var result = array_elements.reduce(function(p, c){
    if (c in p) {
       p[c]++;
    } else {
       p[c]=1;
    }
    return p;
}, {});

​console.log(result);​

The live demo.

note: reduce need a shim for old browsers.

xdazz
  • 158,678
  • 38
  • 247
  • 274
2
var arr = ["2","1","2","2","3","4","3","3","3","5"];
var k = {};

//push into hashtable
for(i in arr){
 k[arr[i]]=(k[arr[i]]||0)+1; //increments count if element already exists
}

//result
for(var j in k) {
 console.log(j+" comes -> "+k[j]+" times");
}
Daniele Urania
  • 2,658
  • 1
  • 15
  • 11
prashanth
  • 2,059
  • 12
  • 13