Total up the instances of items in an array.
31/01/2019 — 1 Min Read — In JavaScript, ES6
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}
PreviousImplicit return object