Sum identical elements within one array in JavaScript

We are required to write a JavaScript function that takes in an array of numbers. The array might contain some repeating / duplicate entries within it. Our function should add all the duplicate entries and return the new array thus formed.

Example

The code for this will be ?

const arr = [20, 20, 20, 10, 10, 5, 1];

const sumIdentical = (arr = []) => {
    let map = {};
    for (let i = 0; i < arr.length; i++) {
        let el = arr[i];
        map[el] = map[el] ? map[el] + 1 : 1;
    };
    
    const res = [];
    for (let count in map) {
        res.push(map[count] * count);
    };
    return res;
};

console.log(sumIdentical(arr));

Output

And the output in the console will be ?

[ 1, 5, 20, 60 ]

How It Works

The function uses an object as a hash map to count occurrences of each element. First, it iterates through the array and stores each unique number as a key with its frequency as the value. Then it multiplies each unique number by its count and pushes the result to the output array.

Alternative Method Using reduce()

Here's a more concise approach using the reduce method:

const arr = [20, 20, 20, 10, 10, 5, 1];

const sumIdenticalReduce = (arr = []) => {
    const counts = arr.reduce((acc, num) => {
        acc[num] = (acc[num] || 0) + 1;
        return acc;
    }, {});
    
    return Object.keys(counts).map(key => key * counts[key]);
};

console.log(sumIdenticalReduce(arr));
[ 20, 60, 5, 1 ]

Conclusion

Both methods effectively sum identical elements by counting occurrences and multiplying by their values. The reduce approach is more functional and concise, while the for-loop method is more explicit and easier to understand.

Updated on: 2026-03-15T23:19:00+05:30

336 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements