Count the number of occurrences of each item in an array - Javascript Array Operation

Javascript examples for Array Operation:Array Search

Description

Count the number of occurrences of each item in an array

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript">
    window.onload=function(){/*w  w w. j  a va  2  s  .c om*/
var arr = ['abc','pq','mn','abc','mn','abc'];
var obj = { };
for (var i = 0, j = arr.length; i < j; i++) {
   if (obj[arr[i]]) {
      obj[arr[i]]++;
   }
   else {
      obj[arr[i]] = 1;
   }
}
console.log(obj);
    }

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

Related Tutorials