JavaScript Sum of two objects with same properties

In JavaScript, summing two objects with identical properties is a common task when working with data aggregation. This involves creating a new object where each property's value is the sum of corresponding values from the input objects.

In JavaScript, objects are data structures that store key-value pairs. When you have multiple objects with the same property names, you often need to combine their values mathematically.

Understanding the Problem

When you have two objects with the same property names, the goal is to create a new object where each property's value is the sum of the matching values from both objects.

For example, given these two objects:

const obj1 = {
    a: 12, 
    b: 8, 
    c: 17
};

const obj2 = {
    a: 2, 
    b: 4, 
    c: 1
};

console.log("Object 1:", obj1);
console.log("Object 2:", obj2);
Object 1: { a: 12, b: 8, c: 17 }
Object 2: { a: 2, b: 4, c: 1 }

The desired result should be:

const result = {
    a: 14,  // 12 + 2
    b: 12,  // 8 + 4
    c: 18   // 17 + 1
};

Method 1: Using reduce() with for...in Loop

This approach uses the reduce method to accumulate values from multiple objects:

const obj1 = { a: 12, b: 8, c: 17 };
const obj2 = { a: 2, b: 4, c: 1 };

const sumObjectsByKey = (...objs) => {
    return objs.reduce((result, currentObj) => {
        for (let key in currentObj) {
            if (currentObj.hasOwnProperty(key)) {
                result[key] = (result[key] || 0) + currentObj[key];
            }
        }
        return result;
    }, {});
};

console.log(sumObjectsByKey(obj1, obj2));
{ a: 14, b: 12, c: 18 }

Method 2: Using Object.keys() and forEach

This method explicitly gets all keys from the first object and sums corresponding values:

const obj1 = { a: 10, b: 20, c: 30 };
const obj2 = { a: 5, b: 15, c: 25 };

function sumTwoObjects(objA, objB) {
    const result = {};
    
    Object.keys(objA).forEach(key => {
        result[key] = objA[key] + (objB[key] || 0);
    });
    
    return result;
}

console.log(sumTwoObjects(obj1, obj2));
{ a: 15, b: 35, c: 55 }

Method 3: Handling Multiple Objects

This enhanced version can handle any number of objects:

const obj1 = { x: 1, y: 2, z: 3 };
const obj2 = { x: 4, y: 5, z: 6 };
const obj3 = { x: 7, y: 8, z: 9 };

function sumMultipleObjects(...objects) {
    const allKeys = new Set();
    
    // Get all unique keys
    objects.forEach(obj => {
        Object.keys(obj).forEach(key => allKeys.add(key));
    });
    
    const result = {};
    
    // Sum values for each key
    allKeys.forEach(key => {
        result[key] = objects.reduce((sum, obj) => {
            return sum + (obj[key] || 0);
        }, 0);
    });
    
    return result;
}

console.log(sumMultipleObjects(obj1, obj2, obj3));
{ x: 12, y: 15, z: 18 }

Comparison

Method Multiple Objects Handles Missing Keys Performance
reduce() + for...in Yes Yes Good
Object.keys() + forEach No (two objects) Yes Better
Enhanced version Yes Yes Good

Key Points

  • Use hasOwnProperty() to ensure you're only processing direct object properties
  • Initialize missing properties to 0 to avoid NaN results
  • The rest parameter (...) allows functions to accept any number of objects
  • reduce() is ideal for accumulating values across multiple objects

Conclusion

Summing objects with identical properties is efficiently handled using reduce() with for...in loops or Object.keys() methods. The reduce approach is most versatile for handling multiple objects dynamically.

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements