I was given this task: Calculate amount of elements in collection by property: "name"
let array = [
{name: 'Serhii'},
{name: 'Serhii'},
{name: 'Nile'},
{name: 'Apple'},
{name: 'Serhii'},
{name: 'Serhii'},
{name: 'Apple'},
{name: 'Serhii'},
];
Here is my solution:
function calculateElements(property, arr) {
let amount = {};
arr.forEach((e) => {
let p = e[property];
p in amount ? amount[p]++ : amount[p] = 1;
});
return amount;
}
console.log(calculateElements('name', array));
Is there more efficient way to do it?