Sum all duplicate value in array - JavaScript

We are required to write a JavaScript function that takes in an array of numbers with duplicate entries and sums all the duplicate entries to one index.

For example −

If the input array is −

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

Then the output should be −

const output = [2, 6, 7, 10, 4];

Using Map to Track and Sum Duplicates

The most efficient approach is to use a Map to count occurrences and then multiply each unique value by its count:

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

const sumDuplicate = arr => {
    const countMap = new Map();
    
    // Count occurrences of each value
    arr.forEach(val => {
        countMap.set(val, (countMap.get(val) || 0) + 1);
    });
    
    // Convert to array: value * count for each unique value
    return Array.from(countMap, ([value, count]) => value * count);
};

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

Using Object-Based Approach

Alternative method using a plain object instead of Map:

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

const sumDuplicateWithObject = arr => {
    const counts = {};
    
    // Count occurrences
    arr.forEach(val => {
        counts[val] = (counts[val] || 0) + 1;
    });
    
    // Return array of value * count
    return Object.entries(counts).map(([value, count]) => +value * count);
};

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

How It Works

The algorithm works in two steps:

  1. Count Phase: Iterate through the array and count how many times each number appears
  2. Sum Phase: For each unique number, multiply it by its count (this gives the "sum" of all duplicates)

For example, if 3 appears twice in [1, 3, 1, 3, 5], the result includes 3 × 2 = 6.

Comparison

Method Performance Memory Readability
Map-based O(n) Lower High
Object-based O(n) Slightly higher High

Conclusion

Both approaches efficiently solve the problem in O(n) time. The Map-based method is slightly more memory-efficient, while the object-based approach might be more familiar to some developers.

Updated on: 2026-03-15T23:18:59+05:30

492 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements