Finding sum of all unique elements in JavaScript

In JavaScript, you can sum duplicate elements by counting their occurrences and multiplying each unique value by its count. This technique is useful for consolidating arrays with repeated values.

For example, if the input array is:

const input = [1, 3, 1, 3, 5, 7, 5, 4];

The output should be:

[2, 6, 10, 7, 4]

This means: 1 appears 2 times (1×2=2), 3 appears 2 times (3×2=6), 5 appears 2 times (5×2=10), while 7 and 4 appear once each.

Using Map to Count and Sum

The most efficient approach uses a Map to count occurrences, then multiplies each unique value by its count:

const input = [1, 3, 1, 3, 5, 7, 5, 4];

const mergeDuplicates = arr => {
    const map = arr.reduce((acc, val) => {
        if(acc.has(val)){
            acc.set(val, acc.get(val) + 1);
        }else{
            acc.set(val, 1);
        };
        return acc;
    }, new Map());
    return Array.from(map, el => el[0] * el[1]);
};

console.log(mergeDuplicates(input));
[ 2, 6, 10, 7, 4 ]

Using Object for Counting

Alternatively, you can use a plain object instead of a Map:

const input = [1, 3, 1, 3, 5, 7, 5, 4];

const mergeDuplicatesWithObject = arr => {
    const counts = {};
    
    // Count occurrences
    arr.forEach(num => {
        counts[num] = (counts[num] || 0) + 1;
    });
    
    // Convert to array of sums
    return Object.entries(counts).map(([key, count]) => key * count);
};

console.log(mergeDuplicatesWithObject(input));
[ 2, 6, 10, 7, 4 ]

How It Works

The algorithm follows these steps:

  1. Count occurrences: Use Map or object to track how many times each number appears
  2. Calculate sums: Multiply each unique number by its occurrence count
  3. Return array: Convert the results back to an array format

Comparison

Method Data Structure Performance Readability
Map approach Map Excellent Good
Object approach Object Good Better

Conclusion

Both approaches effectively sum duplicate elements by counting occurrences first. The Map method is slightly more performant, while the object approach offers better readability for most developers.

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

254 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements