Skip to content Skip to sidebar Skip to footer

Count Each Array Item Occurrence And Return Result As An Object

Any native alternatives for going from: const colorArray = ['red', 'green', 'green', 'blue', 'purple', 'red', 'red', 'black']; to: Object { 'red': 3, 'green': 2, 'blue': 1,

Solution 1:

Array.prototype.reduce() seems to be pretty close to what you're looking for:

const src = ['red', 'green', 'green', 'blue', 'purple', 'red', 'red', 'black'],

      result = src.reduce((acc,color) => (acc[color]=(acc[color]||0)+1, acc), {})
      
console.log(result)
.as-console-wrapper{min-height:100%;}

Solution 2:

Use .reduce:

const colorArray = ['red', 'green', 'green', 'blue', 'purple', 'red', 'red', 'black'];

let colorCount = colorArray.reduce((a, c) => ({ ...a, [c]: a[c] + 1 || 1}), {} );
      
console.log(colorCount);

Post a Comment for "Count Each Array Item Occurrence And Return Result As An Object"