Combine unique items of an array of arrays while summing values - JavaScript

We have an array of arrays, where each subarray contains exactly two elements: a string (person name) and an integer (value). Our goal is to combine subarrays with the same first element and sum their second elements.

For example, this input array:

const example = [
    ['first', 12],
    ['second', 19], 
    ['first', 7]
];

Should be converted to:

[
    ['first', 19],
    ['second', 19]
]

Solution Using Object Mapping

We'll create a function that uses an object to track names and accumulate their values:

const people = [
    ['Ram', 21],
    ['Mohan', 33],
    ['Vikram', 25],
    ['Mike', 29],
    ['Mohan', 41],
    ['Vikram', 26]
];

const combineArray = (people) => {
    const map = {};
    
    for (const index in people) {
        const name = people[index][0];
        const value = people[index][1];
        
        if (map[name]) {
            map[name] += value;
        } else {
            map[name] = value;
        }
    }
    
    return Object.keys(map).map(key => [key, map[key]]);
};

console.log(combineArray(people));
[ [ 'Ram', 21 ], [ 'Mohan', 74 ], [ 'Vikram', 51 ], [ 'Mike', 29 ] ]

Alternative: Using Array.reduce()

A more functional approach using the reduce method:

const combineArrayReduce = (people) => {
    const map = people.reduce((acc, [name, value]) => {
        acc[name] = (acc[name] || 0) + value;
        return acc;
    }, {});
    
    return Object.entries(map);
};

console.log(combineArrayReduce(people));
[ [ 'Ram', 21 ], [ 'Mohan', 74 ], [ 'Vikram', 51 ], [ 'Mike', 29 ] ]

How It Works

The algorithm follows these steps:

  1. Create an empty object to store name-value mappings
  2. Iterate through each subarray in the input
  3. Extract the name and value from each subarray
  4. If the name exists in the object, add the value to the existing sum
  5. If the name doesn't exist, create a new entry
  6. Convert the object back to an array of arrays using Object.entries() or mapping

Complexity Analysis

Aspect Complexity Explanation
Time O(n) Single pass through input array
Space O(n) Object storage for unique names

Conclusion

This approach efficiently combines duplicate entries by using object mapping to accumulate values. The reduce method provides a more functional alternative while maintaining the same O(n) complexity.

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

506 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements