Javascript Data Type How to - Count Array element occurrences








Question

We would like to know how to count Array element occurrences.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from w w w . jav  a 2  s.  co  m-->
var arr1 = [0,0,0,1,2,3,4,3,2,3,4,3,4,3,5];
var arr2 = [];
for (var i = 0; i < arr1.length; i++) {
   if (arr2[arr1[i]] != undefined)
       arr2[arr1[i]]++;
   else
       arr2[arr1[i]] = 1;
}
document.writeln(arr2);

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: