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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With