Sum all similar elements in one array - JavaScript

We are required to write a JavaScript function that takes in an array of numbers and sums all the identical numbers together at one index, removing duplicates while preserving the first occurrence position.

For example, if we have repeated numbers in an array, we want to combine them into a single sum at the position where they first appear.

Problem Statement

If the input array is:

const arr = [20, 10, 15, 20, 15, 10];

Then the output should be:

const output = [40, 20, 30];

Here, 20 appears twice (20 + 20 = 40), 10 appears twice (10 + 10 = 20), and 15 appears twice (15 + 15 = 30).

Using In-Place Array Modification

This approach modifies the original array by finding duplicates and summing them at the first occurrence:

const arr = [20, 10, 15, 20, 15, 10];

const addSimilar = arr => {
    for(let i = 0; i 

[ 40, 20, 30 ]

How It Works

The algorithm works by:

  1. Iterating through each element in the array
  2. For each element, checking if it appears later in the array using lastIndexOf()
  3. If duplicates exist, adding the last occurrence to the current element
  4. Removing the duplicate using splice()
  5. Repeating until no more duplicates of the current element exist

Alternative Approach Using Object Map

A cleaner approach uses an object to track sums and positions:

const arr = [20, 10, 15, 20, 15, 10];

const addSimilarClean = arr => {
    const seen = {};
    const result = [];
    
    for(let num of arr) {
        if(!seen[num]) {
            seen[num] = num;
            result.push(num);
        } else {
            seen[num] += num;
            // Update the existing entry in result
            const index = result.findIndex(val => val === seen[num] - num);
            if(index !== -1) {
                result[index] = seen[num];
            }
        }
    }
    return result;
};

console.log(addSimilarClean([20, 10, 15, 20, 15, 10]));
[ 40, 20, 30 ]

Comparison

Method Modifies Original? Time Complexity Readability
In-place modification Yes O(n²) Complex
Object mapping No O(n) Better

Conclusion

Both methods achieve the same result of summing similar elements. The in-place approach modifies the original array, while the object mapping approach is more efficient and readable for larger datasets.

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

461 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements