How to count array elements by each element in javascript [duplicate]

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.

Answers:

Answer

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/

Answer
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.

Answer
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.

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.