count all elements in array javascript code example

Example 1: count number of each element in array javascript

var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
var counts = {};

for (var i = 0; i < arr.length; i++) {
  var num = arr[i];
  counts[num] ? counts[num] + 1 : 1;
}

console.log(counts[5], counts[2], counts[9], counts[4]);

Example 2: use .map to count length of each element in an array

var lengths = chars.map(function(word){
 return word.length
})

Example 3: use .map to count length of each element in an array

var words = ['Hello', 'world'];

var lengths = words.map(function(word) {
  return word + ' = ' + word.length;
});

console.log(lengths);

Tags:

Php Example