DEV Community

loading...
Cover image for Count by the properties of an array of objects

Count by the properties of an array of objects

syedsimanta03
UI designer | Front end developer | Graphic designer #OpenToWork » Tools: GIT, VS Code, Adobe XD, Figma, Photoshop, Illustrator
・1 min read

Count by the properties of an array of objects

const countBy = (arr, prop) => arr.reduce((prev, curr) => (prev[curr[prop]] = ++prev[curr[prop]] || 1, prev), {});

// Example
countBy([
{ branch: 'audi', model: 'q8', year: '2019' },
{ branch: 'audi', model: 'rs7', year: '2020' },
{ branch: 'ford', model: 'mustang', year: '2019' },
{ branch: 'ford', model: 'explorer', year: '2020' },
{ branch: 'bmw', model: 'x7', year: '2020' },
], 'branch');

// { 'audi': 2, 'ford': 2, 'bmw': 1 }

Discussion (0)