patternjavascriptMinor
Calculate amount of elements in collection by property
Viewed 0 times
elementsamountcollectionpropertycalculate
Problem
I was given this task: Calculate amount of elements in collection by property: "name"
Here is my solution:
Is there more efficient way to do it?
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?
Solution
That looks quite fine to me. You can remove the parentheses around
If you're really going for efficiency, a regular
e in the arrow function.If you're really going for efficiency, a regular
for loop is faster than the .forEach() method. That can help if you have a very large amount of objects to process and need to display a result instantly to a user, but otherwise the optimization is unnecessary for what you're trying to accomplish.Context
StackExchange Code Review Q#143997, answer score: 2
Revisions (0)
No revisions yet.