Total up the instances of items in an array

JavaScript, ES6

Count the occurrences of each item in an array using reduce.

Explanation

  • reduce((obj, itm) => { ... }, {}): This method executes a reducer function on each element of the array, resulting in a single output value.

Usage

To count the instances of items in an array, use the following code:

const data = [
  'bmw',
  'bmw',
  'lamborghini',
  'audi',
  'lamborghini',
  'bmw',
  'audi',
];

const counting = data.reduce((obj, itm) => {
  if (!obj[itm]) {
    obj[itm] = 0;
  }
  obj[itm]++;
  return obj;
}, {});

console.log(counting);
// {bmw: 3, lamborghini: 2, audi: 2}