Sum JavaScript arrays repeated value

Suppose, we have an array of objects like this −

const arr = [ {'TR-01':1}, {'TR-02':3}, {'TR-01':3}, {'TR-02':5}];

We are required to write a JavaScript function that takes in one such array and sums the value of all identical keys together.

Therefore, the summed array should look like −

const output = [ {'TR-01':4}, {'TR-02':8}];

Method 1: Using In-Place Modification

This approach modifies the original array by tracking duplicate keys and summing their values:

const arr = [ {'TR-01':1}, {'TR-02':3}, {'TR-01':3}, {'TR-02':5}];

const sumDuplicate = arr => {
    const map = {};
    for(let i = 0; i 

[ { 'TR-01': 4 }, { 'TR-02': 8 } ]

Method 2: Using reduce() (Immutable)

This approach creates a new array without modifying the original:

const arr = [ {'TR-01':1}, {'TR-02':3}, {'TR-01':3}, {'TR-02':5}];

const sumDuplicate = arr => {
    const result = {};
    
    arr.forEach(obj => {
        const key = Object.keys(obj)[0];
        const value = obj[key];
        result[key] = (result[key] || 0) + value;
    });
    
    return Object.keys(result).map(key => ({[key]: result[key]}));
};

const summedArray = sumDuplicate(arr);
console.log(summedArray);
console.log('Original array unchanged:', arr);
[ { 'TR-01': 4 }, { 'TR-02': 8 } ]
Original array unchanged: [ { 'TR-01': 1 }, { 'TR-02': 3 }, { 'TR-01': 3 }, { 'TR-02': 5 } ]

How It Works

Both methods follow the same logic:

  • Extract keys: Get the first (and only) key from each object
  • Track duplicates: Use a map/object to store key positions or accumulated values
  • Sum values: Add values for duplicate keys together
  • Remove/avoid duplicates: Either splice the array or create a new one

Comparison

Method Modifies Original Performance Readability
In-place modification Yes Slower (splice operations) Complex
Using reduce/forEach No Faster Better

Conclusion

The immutable approach using forEach and object accumulation is generally preferred as it's more readable and doesn't modify the original data. Use the in-place method only when memory conservation is critical.

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

345 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements