Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
55
rated 0 times [  60] [ 5]  / answers: 1 / hits: 37482  / 12 Years ago, fri, october 5, 2012, 12:00:00

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.


More From » javascript

 Answers
68

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/


[#82731] Thursday, October 4, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zariahdiamondz

Total Points: 649
Total Questions: 109
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;