Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 846
suresh.g Avatar asked Nov 28 '22 00:11

suresh.g


2 Answers

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.

like image 86
I Hate Lazy Avatar answered Dec 10 '22 01:12

I Hate Lazy


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/

like image 21
Guffa Avatar answered Dec 10 '22 03:12

Guffa