First iterate through the array and push the 'name' into another object's property. If the property exists add the 'value' to the value of the property otherwise initialize the property to the 'value'. Once you build this object, iterate through the properties and push them to another array.

Here is some code:

Copyvar obj = [
    { 'name': 'P1', 'value': 150 },
    { 'name': 'P1', 'value': 150 },
    { 'name': 'P2', 'value': 200 },
    { 'name': 'P3', 'value': 450 }
];

var holder = {};

obj.forEach(function(d) {
  if (holder.hasOwnProperty(d.name)) {
    holder[d.name] = holder[d.name] + d.value;
  } else {
    holder[d.name] = d.value;
  }
});

var obj2 = [];

for (var prop in holder) {
  obj2.push({ name: prop, value: holder[prop] });
}

console.log(obj2);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Hope this helps.

Answer from link on Stack Overflow
Top answer
1 of 16
44

First iterate through the array and push the 'name' into another object's property. If the property exists add the 'value' to the value of the property otherwise initialize the property to the 'value'. Once you build this object, iterate through the properties and push them to another array.

Here is some code:

Copyvar obj = [
    { 'name': 'P1', 'value': 150 },
    { 'name': 'P1', 'value': 150 },
    { 'name': 'P2', 'value': 200 },
    { 'name': 'P3', 'value': 450 }
];

var holder = {};

obj.forEach(function(d) {
  if (holder.hasOwnProperty(d.name)) {
    holder[d.name] = holder[d.name] + d.value;
  } else {
    holder[d.name] = d.value;
  }
});

var obj2 = [];

for (var prop in holder) {
  obj2.push({ name: prop, value: holder[prop] });
}

console.log(obj2);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Hope this helps.

2 of 16
36

An ES2024 approach to group by name

You can first use Map.groupBy to group your array by name into Map where each key in the map is a name from your objects and the value is an array of objects from your array with that name key. You can then use Array.from() on the grouped Map to convert it into an array of objects, where for each object, you accumulate the objects to sum on value with the same name key using .reduce():

Copyconst sumByKey = (arr, key, value) => {
  const grouped = Map.groupBy(arr, o => o[key]);
  return Array.from(
    grouped.values(),
    group => group.reduce((acc, obj) => ({...obj, [value]: (acc[value] ?? 0) + obj[value]}), {})
  );
}

const arr = [ { 'name': 'P1', 'value': 150 }, { 'name': 'P1', 'value': 150 }, { 'name': 'P2', 'value': 200 }, { 'name': 'P3', 'value': 450 } ];
console.log(sumByKey(arr, 'name', 'value')); // [ { "name": "P1", "value": 300 }, { "name": "P2", "value": 200 }, { "name": "P3", "value": 450 } ]
Run code snippetEdit code snippet Hide Results Copy to answer Expand

An ES6 approach to group by name:

You can convert your array of objects to a Map by using .reduce(). The Map has key-value pairs, where each key is the name, and each value is the accumulated sum of values for that particular name key. You can then easily convert the Map back into an array using Array.from(), where you can provide a mapping function that will take the keys/values of the Map and convert them into objects:

Copyconst arr = [ { 'name': 'P1', 'value': 150 }, { 'name': 'P1', 'value': 150 }, { 'name': 'P2', 'value': 200 }, { 'name': 'P3', 'value': 450 } ];

const res = Array.from(arr.reduce(
  (m, {name, value}) => m.set(name, (m.get(name) || 0) + value), new Map
), ([name, value]) => ({name, value}));
console.log(res);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

The above is quite compact and not necessarily the easiest to read. I would suggest putting it into a function so it's clearer what it's doing. If you're after more self-documenting code, using for...of can make the above easier to understand. The below function is also useful if you want to group or sum on keys with spaces in them:

Copyconst arr = [ { 'name': 'P1', 'value': 150 }, { 'name': 'P1', 'value': 150 }, { 'name': 'P2', 'value': 200 }, { 'name': 'P3', 'value': 450 } ];

const sumByKey = (arr, key, value) => {
  const map = new Map();
  for(const obj of arr) {
    const currSum = map.get(obj[key]) || 0;
    map.set(obj[key], currSum + obj[value]);
  }
  const res = Array.from(map, ([k, v]) => ({[key]: k, [value]: v}));
  return res;
}

console.log(sumByKey(arr, 'name', 'value')); // 'name' = value to group by, 'value' = value to sum
Run code snippetEdit code snippet Hide Results Copy to answer Expand


Grouping by more than just name:

Here's an approach that should work if you have other overlapping properties other than just name (the keys/values need to be the same in both objects for them to "group"). It involves iterating through your array and reducing it to Map which holds key-value pairs. Each key of the new Map is a string of all the property values you want to group by, and so, if your object key already exists then you know it is a duplicate, which means you can add the object's current value to the stored object. Finally, you can use Array.from() to transform your Map of key-value pairs, to an array of just values:

Copyconst arr = [{'name':'P1','value':150},{'name':'P1','value':150},{'name':'P2','value':200},{'name':'P3','value':450}];

const res = Array.from(arr.reduce((acc, {value, ...r}) => {
  const key = JSON.stringify(r);
  const current = acc.get(key) || {...r, value: 0};  
  return acc.set(key, {...current, value: current.value + value});
}, new Map).values());
console.log(res);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

🌐
Tuts Make
tutsmake.com › home › javascript sum array of objects value by key example
JavaScript Sum Array of Objects Value by Key Example - Tuts Make
December 18, 2023 - Here is an example of the sum array of objects by key using for loop method. var numArr = [ { name: 'a', num: 50}, { name: 'b', num: 50}, { name: 'c', num: 75}, { name: 'd', num: 35}, { name: 'e', num: 25 }, ]; var sum = 0; for (var i = 0; i ...
Discussions

javascript - Sum up nested array of objects based on keys - Code Review Stack Exchange
I have this function that should take some array of objects and sum up the values of the inner objects based on some keys, and conditionally add to it some values from another object. Is there a wa... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
May 13, 2022
javascript - Sum array of objects by unique keys - Code Review Stack Exchange
I have an array of objects, each with a dimensions field for storing various metrics related to the object, e.g. length, width, weight, etc. Each object may be different in terms of what metrics i... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
March 14, 2020
reactjs - How to calculate sum of object keys in array - javascript - Stack Overflow
Question I am working with firebase and react native. I have returned an array from my firebase database that looks like this. [Object, Object, Object] Under each object I have returned a single... More on stackoverflow.com
🌐 stackoverflow.com
Sum up array of Javascript objects by key - Stack Overflow
I have looked through stack overflow and feel like there is a much easier solution using map and reduce to solve this problem but this is my clumsy way to solve it so far. I need to sum up data by ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
gist.github.com › benwells › 0111163b3cccfad0804d994c70de7aa1
Using Array.reduce to sum a property in an array of objects · GitHub
items = [ { customer_id: 1, id: 1, sum: 123} { customer_id: 1, id: 2, sum: 321} { customer_id: 1, id: 3, sum: 213}, ] var total_sum = items.reduce(function(prev, cur) { return prev + cur.summ; }, 0); console.log(total_sum) -> `NaN` %(
Top answer
1 of 3
1

You are returning a new object in each iteration inside the reducers, when you could use just one object for the tallies (see below). The handling of undefined values suggest to me that the underlying data might be invalid, in which case it makes more sense to fix the data and establish validation before insert. Unless of course the values are spec'd to be optional.

const sumKeys = (xs, ys = []) => {
  const sum = {key1: 0, key2: 0}

  for (const obj of xs) {
    for (const item of obj.items) {
      sum.key1 += item.key1 * obj.num
      sum.key2 += item.key2 * obj.num
    }
  }

  for (const obj of ys) {
    sum.key1 += obj.gross * obj.num
    sum.key2 += obj.net * obj.num
  }

  return sum
}
2 of 3
1

I found it useful to ensure that the input data was sanitised to remove the possibility of undefined values before further processing. Much of the verbosity of the code was to do with checking for undefined when the alternate value was always 0, and that even extended to the computeVal function which became redundant.

The sample data was actually 'complete' and didn't include undefined values so I've not tested for outcomes based on imcomplete data. It might also be reasonable to replace || 0 with nullish (?? 0) and to consider if there might be strings or other types that would coerce to falsy and be converted to 0 when something else should happen.

Whilst it would be possible to refactor the nested reduce, it doesn't seem worth it as it now is easier to understand.

I also chose to abbreviate the variable names, again principally to reduce the verbosity without introducing ambiguity.

I suspect that the actual application data doesn't use opaque keys like key1 and key2, I suspect this was used to simplify the question. As a result, this might need a little more work to provide useful defaults, and generally the naming conventions might need aligning with the actual data.

function sanitiseObjects(objects) {
    return objects?.map(obj => {
        return {
            ...obj,
            num: obj.num || 0,
            items: obj.items.map(item => ({
                key1: item.key1 || 0,
                key2: item.key2 || 0,
            }))
        }
    }) || []
}

function sanitizeTotals(totals) {
    return totals?.map(total => ({
        ...total,
        num: total.num || 0,
        gross: total.gross || 0,
        net: total.net || 0,
    })) || []
}

function sumUpKeys(objects, totals = undefined) {

    const defaults = { key1: 0, key2: 0 }

    const totalsSum = sanitizeTotals(totals).reduce((acc, item) => {
        return {
            key1: acc.key1 + (item.num * item.gross),
            key2: acc.key2 + (item.num * item.net),
        };
    }, defaults);

    const objectsSum = sanitiseObjects(objects).reduce((objectsAcc, object) => {
        const itemsSum = object.items.reduce((itemsAcc, item) => {
            return {
                key1: (object.num * item.key1) + itemsAcc.key1,
                key2: (object.num * item.key2) + itemsAcc.key2,
            };
        }, defaults);
        return {
            key1: objectsAcc.key1 + itemsSum.key1,
            key2: objectsAcc.key2 + itemsSum.key2,
        };
    }, defaults);


    // add additional services sum to the monthly charges sum
    return {
        key1: objectsSum.key1 + (totalsSum?.key1 || 0),
        key2: objectsSum.key2 + (totalsSum?.key2 || 0),
    };
}

const objects1 = [
    { num: 3, items: [{ key1: 4, key2: 2, }, { key1: 10, key2: 20, }, ], key3: 'aa', },
    { num: 4, items: [{ key1: 4, key2: 2, }, ], key3: 'aa', },
];

const totals1 = [
    { num: 2, gross: 10, net: 5,},
    { num: 3, gross: 6, net: 12,},
];

// result with totals
const result1 = sumUpKeys(objects1, totals1);
// result without totals
const result2 = sumUpKeys(objects1);
console.log(result1);
console.log(result2);

Find elsewhere
🌐
YouTube
youtube.com › watch
How to Get the Sum of Specific Keys Values from an Array of Objects in JavaScript - YouTube
This guide explores how to sum values from an array of objects based on specific keys using JavaScript, specifically focusing on the `reduce` method for effe...
Published   April 1, 2025
Views   1
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › reduce
Array.prototype.reduce() - JavaScript - MDN Web Docs
July 20, 2025 - Some of the acceptable use cases of reduce() are given above (most notably, summing an array, promise sequencing, and function piping). There are other cases where better alternatives than reduce() exist. Flattening an array of arrays. Use flat() instead. ... Grouping objects by a property. Use Object.groupBy() instead. ... const groups = array.reduce((acc, obj) => { const key = obj.name; const curGroup = acc[key] ??
🌐
EyeHunts
tutorial.eyehunts.com › home › javascript sum array of objects | example code
JavaScript sum array of objects | Example code
April 24, 2023 - function count(array, key) { return array.reduce(function (r, a) { return r + a[key]; }, 0); } var array = [{ "adults": 2, "children": 3 }, { "adults": 2, "children": 2 }], adults = count(array, 'adults'), children = count(array, 'children'); ...
🌐
DevelopersLearnIt
developerslearnit.com › home › javascript › ordering, grouping by key and sum an array of objects in javascript
Ordering, Grouping by Key and Sum An Array of Objects in JavaScript
January 21, 2024 - For clarity, given an array of orders objects like the one on the left, we are to return the result like what we have on the right. We are going to solve this issue in three different ways. Let's dive into solving this. Let's list out the step we will take to implement the first method: ... f the customer name is not present in the finalResult array, then add the customer name and the order amount to the finalResult array
🌐
Barbara
geekiebarbs.hashnode.dev › how-to-sum-the-values-of-an-object-in-javascript
How to Sum the Values of an Object in JavaScript - Barbara
August 18, 2023 - The for...in loop iterates over the object's properties and allows us to access each value and once the loop has iterated over all of the object's properties we have the sum of the values. ... let salaries ={ John: 100, Ann: 160, Pete: 130, } let sum = 0; for (const key in salaries) { sum += salaries[key]; } console.log(sum); // 390
🌐
Delft Stack
delftstack.com › home › howto › javascript › sum array of objects javascript
How to Sum Array of Objects in JavaScript | Delft Stack
March 11, 2025 - This tutorial demonstrates how to sum an array of objects in JavaScript using various methods, including reduce, forEach, and for...of loops. Learn the best practices for efficiently handling data and summing properties like amounts in your JavaScript projects.
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-get-sum-of-array-object-values
How to Sum a Property in an Array of Objects in JavaScript | bobbyhadz
March 2, 2024 - Copied!const arr = [ {id: 1, salary: 10}, {id: 2, salary: 20}, {id: 3, salary: 30}, ]; const sum = arr.reduce((accumulator, object) => { return accumulator + object.salary; }, 0); console.log(sum); // 👉️ 60 ... The function we passed to the Array.reduce() method gets invoked for each element (object) in the array. The accumulator parameter gets an initial value of 0 because that's what we supplied as the second argument to the reduce() method. We increment the accumulator by the value of the salary property for each object in the array.
🌐
Mish Ushakov
mish.co › posts › sum-and-average-array-of-objects-in-js
Sum and average Array of Objects in JavaScript - Mish Ushakov
October 23, 2021 - If current element is the last in the array, divide the current key by array length · If you want to calculate on multiple arrays, you can concatenate them using the spread operator · const sample = [...sample_a, ...sample_b] Now you should be able to understand how to calculate the sum of ...