A cleaner way to accomplish this is by providing an initial value as the second argument to reduce:

Copyvar arr = [{x:1}, {x:2}, {x:4}];
var result = arr.reduce(function (acc, obj) { return acc + obj.x; }, 0);
console.log(result);  // 7
Run code snippetEdit code snippet Hide Results Copy to answer Expand

The first time the anonymous function is called, it gets called with (0, {x: 1}) and returns 0 + 1 = 1. The next time, it gets called with (1, {x: 2}) and returns 1 + 2 = 3. It's then called with (3, {x: 4}), finally returning 7.

This also handles the case where the array is empty, returning 0.

Answer from Casey Chu on Stack Overflow
Top answer
1 of 16
496

A cleaner way to accomplish this is by providing an initial value as the second argument to reduce:

Copyvar arr = [{x:1}, {x:2}, {x:4}];
var result = arr.reduce(function (acc, obj) { return acc + obj.x; }, 0);
console.log(result);  // 7
Run code snippetEdit code snippet Hide Results Copy to answer Expand

The first time the anonymous function is called, it gets called with (0, {x: 1}) and returns 0 + 1 = 1. The next time, it gets called with (1, {x: 2}) and returns 1 + 2 = 3. It's then called with (3, {x: 4}), finally returning 7.

This also handles the case where the array is empty, returning 0.

2 of 16
414

After the first iteration your're returning a number and then trying to get property x of it to add to the next object which is undefined and maths involving undefined results in NaN.

try returning an object contain an x property with the sum of the x properties of the parameters:

Copyvar arr = [{x:1},{x:2},{x:4}];

arr.reduce(function (a, b) {
  return {x: a.x + b.x}; // returns object with property x
})

// ES6
arr.reduce((a, b) => ({x: a.x + b.x}));

// -> {x: 7}

Explanation added from comments:

The return value of each iteration of [].reduce used as the a variable in the next iteration.

Iteration 1: a = {x:1}, b = {x:2}, {x: 3} assigned to a in Iteration 2

Iteration 2: a = {x:3}, b = {x:4}.

The problem with your example is that you're returning a number literal.

Copyfunction (a, b) {
  return a.x + b.x; // returns number literal
}

Iteration 1: a = {x:1}, b = {x:2}, // returns 3 as a in next iteration

Iteration 2: a = 3, b = {x:2} returns NaN

A number literal 3 does not (typically) have a property called x so it's undefined and undefined + b.x returns NaN and NaN + <anything> is always NaN

Clarification: I prefer my method over the other top answer in this thread as I disagree with the idea that passing an optional parameter to reduce with a magic number to get out a number primitive is cleaner. It may result in fewer lines written but imo it is less readable.

๐ŸŒ
GitHub
gist.github.com โ€บ benwells โ€บ 0111163b3cccfad0804d994c70de7aa1
Using Array.reduce to sum a property in an array of objects ยท GitHub
var items = [ { name: 'Item 1', ... 0 } ]; var msgTotal = items.reduce(function(prev, cur) { return prev + (cur.amount - (cur.amount * cur.discount) ); }, 0); document.write('Total of Discounted Items:', msgTotal);...
Discussions

How to reduce and sum a nested object array?
// reduce product to sum via matching keys const productReducer = (sumObj, product) => { const current = sumObj[product.productName] || 0; return { ...sumObj, [product.productName]: current + product.total } } // reduce product, return [key, product] const hourMapper = ([key, hours]) => { return [key, hours.reduce(productReducer, {})]; } // restore [key, val] array to object const flattenKeyVal = (obj, keyVal) => { return { ...obj, [keyVal[0]]: keyVal[1] } } // obj -> [key,product] -> [key, reducedProduct] -> reducedObj const dayMapper = day => { return Object.entries(day).map(hourMapper).reduce(flattenKeyVal); } // put it all together for the days const mapDays = days => days.map(dayMapper); I believe this should work! Fun little challenge. Let me know if you have any questions. More on reddit.com
๐ŸŒ r/learnjavascript
6
2
May 3, 2021
javascript - reduce & sum array of objects entries - Stack Overflow
But I cannot find a way to also sum the Budget figures together and add it to the same entry. I suspect I need to perform a separate reduce function on a duplicate array and push the result into the res array using the forEach loop with Year as the key. Can anyone see a way of doing this in the same reduce function? ... When initializing a Year object ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
javascript - Using reduce to calculate the sum of an array of objects - Stack Overflow
I am trying to compute the sum of the weight of an array of object with children, however I think I am doing it the wrong way. I am trying to present a list of parcels using a searchable dropdown p... More on stackoverflow.com
๐ŸŒ stackoverflow.com
June 13, 2019
[deleted by user]
Honestly, just use reduce if you need to go from a collection of stufff to a single value. If you are using it for other things, you are probably abusing it More on reddit.com
๐ŸŒ r/reactjs
95
160
November 2, 2022
๐ŸŒ
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 - The value returned by reduce() in this case would be 95. To sum up the values contained in an array of objects, you must supply an initialValue, so that each item passes through your function.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-sum-a-javascript-array-with-reduce
How to sum a JavaScript array with reduce
If you are afraid of arrow functions, here is the traditional way: function sumArray(array) { /*Go through array and loop total starting point is 1 and item = 4 */ const sum = array.reduce(function(total, item) { return total + item; }); /* ...
๐ŸŒ
DEV Community
dev.to โ€บ shubhamtiwari909 โ€บ reduce-method-to-sum-values-of-array-of-objects-33bk
Reduce method to sum values of array of objects - DEV Community
September 14, 2021 - Perhaps the easiest-to-understand case for reduce() is to return the sum of all the elements in an array. ... import React from 'react' function App() { const data = [ { Name : "shubham", Marks:100 }, { Name : "bharat", Marks:90 }, { Name : "abhishek", Marks:80 }, { Name : "himanshu", Marks:90 }, { Name : "alfiya", Marks:68 }, { Name : "akshay", Marks:79 } ]; var total = data.reduce((accum,item) => accum + item.Marks, 0) return ( <div> {data.map((item) => ( <div className="m-5" style={{display:"grid",gridTemplateColumns:"repeat(2,1fr)",justifyContent:"center"}}> <p>{item.Name}</p> <p>{item.Marks}</p> </div> ))} <div className="m-5" style={{display:"grid",gridTemplateColumns:"repeat(2,1fr)",justifyContent:"center"}}> <p></p> <p className="my-5">{total}</p> </div> </div> ) } export default App
๐ŸŒ
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 - In this example, we have an array called data, containing objects with an id and an amount. The reduce() function iterates over each object, using an accumulator to keep a running total of the amount property.
๐ŸŒ
sebhastian
sebhastian.com โ€บ javascript-sum-array-objects
JavaScript code recipe: sum an array of objects | sebhastian
January 18, 2021 - When you call the reduce method on array of objects, you need to always specify the initial value to prevent reduce from using the first object as the initial value. If the cart has quantity data, you can multiply the quantity by price before ...
Find elsewhere
๐ŸŒ
ReqBin
reqbin.com โ€บ code โ€บ javascript โ€บ m81eb1ms โ€บ javascript-sum-array-example
How to get a sum of array elements in JavaScript?
November 24, 2023 - Alternatively, you can find the sum of array elements using a "for" loop. In this JavaScript Array Sum Example, we use the reduce() method to get the sum of the array elements with an initial value.
๐ŸŒ
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 - We increment the accumulator by the value of the salary property for each object in the array. The reduce() method returns the sum of the salary values of all objects in the array.
๐ŸŒ
Dev By RayRay
byrayray.dev โ€บ posts โ€บ 2022-12-19-sum-total-array-object-properties-javascript-reduce-method
How To Sum Total From Array Of Object Properties With JavaScript Reduce Method | Dev By RayRay
The reduce() method iterates through the numbers in the array, starting with the first element, and applies the callback function to each element. The returned value from the callback function becomes the new value for the accumulator, which ...
๐ŸŒ
Redbitdev
redbitdev.com โ€บ post โ€บ using-array-reduce-with-objects
Using Array.reduce With Objects
September 21, 2021 - The final value of 'sum' will be '15'. ... Remember that Array.reduce can use initial and return values of any type, which makes it very flexible. Let's explore how we can use it to perform some common tasks with plain objects.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjavascript โ€บ how to reduce and sum a nested object array?
How to reduce and sum a nested object array? : r/learnjavascript
May 3, 2021 - // reduce product to sum via matching keys const productReducer = (sumObj, product) => { const current = sumObj[product.productName] || 0; return { ...sumObj, [product.productName]: current + product.total } } // reduce product, return [key, product] const hourMapper = ([key, hours]) => { return [key, hours.reduce(productReducer, {})]; } // restore [key, val] array to object const flattenKeyVal = (obj, keyVal) => { return { ...obj, [keyVal[0]]: keyVal[1] } } // obj -> [key,product] -> [key, reducedProduct] -> reducedObj const dayMapper = day => { return Object.entries(day).map(hourMapper).reduce(flattenKeyVal); } // put it all together for the days const mapDays = days => days.map(dayMapper);
๐ŸŒ
Built In
builtin.com โ€บ software-engineering-perspectives โ€บ javascript-reduce
Guide to the JavaScript Reduce() Method | Built In
JavaScript reduce() is a higher order function used in data manipulation that reduces an array to a single value. It takes two parameters: a callback function and an optional initial value.
๐ŸŒ
CoreUI
coreui.io โ€บ answers โ€บ how-to-sum-an-array-of-numbers-in-javascript
How to sum an array of numbers in JavaScript ยท CoreUI
September 29, 2025 - This method is concise, readable, and follows functional programming principles while handling empty arrays gracefully. Use reduce() with an accumulator to sum all array elements.
๐ŸŒ
CodePen
codepen.io โ€บ santhoshjanan โ€บ pen โ€บ OJJpjBG
Javascript Reduce - for group by sum on object array
Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.
Top answer
1 of 1
3

When initializing a Year object in the reduce callback, also initialize a Budget property to 0. Then, on each iteration for that year, add to the budget property in addition to setting the Sample property:

var arr = [{ "Year": 2019, "Title": "Sample1", "Sum": 1020000.0, "Budget":0}, 
  {  "Year": 2019,  "Title": "Sample2",  "Sum": 2546658.0,  "Budget":100},
  {  "Year": 2019,  "Title": "Sample3",  "Sum": 1020000.0,  "Budget":1000},
  {  "Year": 2020,  "Title": "Sample1",  "Sum": 3472000.0,  "Budget":100}, 
  {  "Year": 2020,  "Title": "Sample2",  "Sum": 1020000.0,  "Budget":10},
  {  "Year": 2020,  "Title": "Sample3",  "Sum": 2452000.0,  "Budget":50},
  {  "Year": 2021,  "Title": "Sample1",  "Sum": 1000.0,  "Budget":100}, 
  {  "Year": 2021,  "Title": "Sample2",  "Sum": 119000.0,  "Budget":10},
  {  "Year": 2021,  "Title": "Sample3",  "Sum": 234000.0,  "Budget":50}
]
var res = arr.reduce(function(acc, curr) {
  acc[curr.Year] = acc[curr.Year] || { Year: curr.Year, Budget: 0 } ;
  //                                                    ^^^^^^^^^
  acc[curr.Year][curr.Title] = curr.Sum;
  acc[curr.Year].Budget += curr.Budget;
  // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  return acc;
}, {});
var output = Object.keys(res).map(function(key) {
  return res[key];
});
console.log(output);

Note that the line in your original code

acc[curr.Year] = acc[curr.Year];

doesn't accomplish anything at all - you may omit it entirely.

You could consider using Babel and polyfills, allowing you to write code in the latest and greatest version of the language, while preserving compatibility for obsolete browsers, in which case, the code could be prettified to:

var arr=[{"Year":2019,"Title":"Sample1","Sum":1020000.0,"Budget":0},{"Year":2019,"Title":"Sample2","Sum":2546658.0,"Budget":100},{"Year":2019,"Title":"Sample3","Sum":1020000.0,"Budget":1000},{"Year":2020,"Title":"Sample1","Sum":3472000.0,"Budget":100},{"Year":2020,"Title":"Sample2","Sum":1020000.0,"Budget":10},{"Year":2020,"Title":"Sample3","Sum":2452000.0,"Budget":50},{"Year":2021,"Title":"Sample1","Sum":1000.0,"Budget":100},{"Year":2021,"Title":"Sample2","Sum":119000.0,"Budget":10},{"Year":2021,"Title":"Sample3","Sum":234000.0,"Budget":50}]

const output = Object.values(arr.reduce((a, { Year, Title, Sum, Budget }) => {
  a[Year] = a[Year] || { Year, Budget: 0 };
  a[Year][Title] = Sum;
  a[Year].Budget += Budget;
  return a;
}, {}));
console.log(output);

๐ŸŒ
Treehouse Blog
blog.teamtreehouse.com โ€บ javascript-array-methods-reduce
JavaScript Array Methods: reduce() | Treehouse Blog
September 11, 2023 - In each iteration of the reduce() method, the callback function adds the current element (num) to the accumulator (total), and the result of this operation is stored in the total variable.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 56589048 โ€บ using-reduce-to-calculate-the-sum-of-an-array-of-objects โ€บ 56589530
javascript - Using reduce to calculate the sum of an array of objects - Stack Overflow
June 13, 2019 - `I like ${selectedItemObjects.map((item, i) => { let label = `${item.name}, `; if (i === selectedItemObjects.length - 2) label = `${item.name} and `; if (i === selectedItemObjects.length - 1) label = `${item.name}.`; return label; }).join('')}` : 'Select a parcel'; } addValues = () => { const total = parcelCategories.reduce((result, { children: { value } }) => result.value + value, 0) return total; } render() { return ( <ScrollView keyboardShouldPersistTaps="always" style={{ backgroundColor: '#f8f8f8' }} contentContainerStyle={styles.container}> <Text style={styles.welcome}> React native sectioned multi select example.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ sum-of-array-object-property-values-in-new-array-of-objects-in-javascript
Sum of array object property values in new array of objects in JavaScript
March 15, 2026 - The expected output should be: [ { subject: 'Maths', marks: 70, noOfStudents: 17 }, { subject: 'Science', marks: 115, noOfStudents: 18 }, { subject: 'History', marks: 90, noOfStudents: 43 } ] The most efficient approach uses the reduce() method ...