HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Calculate amount of elements in collection by property

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
elementsamountcollectionpropertycalculate

Problem

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?

Solution

That looks quite fine to me. You can remove the parentheses around 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.