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.

4
  • You want them counted in Ruby or JavaScipt? If the latter, why ruby tags? Commented Oct 5, 2012 at 15:16
  • Do you know how to write a for loop and use an object. Seems like basic homework 101 type of question. Commented Oct 5, 2012 at 15:20
  • 1
    duplicate questions: stackoverflow.com/questions/840781/… and stackoverflow.com/questions/2228362/… Commented Oct 5, 2012 at 15:23
  • 1
    for people who like fancy words, this is a histogram Commented Oct 5, 2012 at 15:23

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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/

Comments

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.

Comments

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");
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.