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

var 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
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › reduce
Array.prototype.reduce() - JavaScript | MDN
This convention propagates to JavaScript's reduce(): you should use spreading or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined.
Top answer
1 of 16
496

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

var 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:

var 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.

function (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.

Discussions

How to reduce array of objects to array
Greetings, Say for example i dont wish to use a for loop or forEach, I also dont wish to map and then do another pass to clear undefined values. how would I say convert an array of objects into different array, want this… More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
13
0
June 12, 2022
Learning array.reduce() method, i need some help to understand it.
How to push Array in to nested Object? I cant use .push() since im trying to add a new key value pair? Ive tried looking at stack overflow and other places but no luck. if anyone can point me in the right direction would be super helpful please :) ... JavaScript does have some bad parts, as does any other programming language, but the good parts of ... More on reddit.com
🌐 r/learnjavascript
68
64
April 12, 2022
Reduce array of nested objects?
Hey guys, got this array of objects that I want to reduce the quantity of each item to a single summed up value. What is the most efficient way of achieving this? cartItems.reduce() is definitely what I’m wanting, but how would I be able to destructure this in the parameters? More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
19
0
January 19, 2021
[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 1, 2022
🌐
Medium
medium.com › @lwkchan › javascripts-array-reduce-method-a-guide-and-a-commendation-on-its-flexibility-ea5dc192fad5
JavaScript’s Array reduce() method: a guide and a commendation on its flexibility | by Laura Chan | Medium
May 17, 2018 - Then, as we actually reduce the sauce by simmering it over low heat, it thickens and reduces in size; we reduce the elements of the array by applying each one to the callback method. What results in both cases is one product: a bolognese sauce and a JavaScript Object.
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
How to reduce array of objects to array - JavaScript - The freeCodeCamp Forum
June 12, 2022 - Greetings, Say for example i dont wish to use a for loop or forEach, I also dont wish to map and then do another pass to clear undefined values. how would I say convert an array of objects into different array, want this input: [ {a:1}, {name: 'Jane'}, {}, {b:2}, {name: 'Smith'}, {name: 'Fatima'}, ] to output e.g. : ['Jane', 'Smith', 'Fatima'] Can it be done using reduce?
🌐
W3Schools
w3schools.com › jsref › jsref_reduce.asp
JavaScript Array reduce() Method
The reduce() method executes a reducer function for array element.
🌐
Reddit
reddit.com › r/learnjavascript › learning array.reduce() method, i need some help to understand it.
r/learnjavascript on Reddit: Learning array.reduce() method, i need some help to understand it.
April 12, 2022 - Reduce iterates over an array and creates an array and passes the newest version of it back into the next iteration. That sounds confusing surely, so just look how the acc comes into each function as a parameter and then goes back out at the ...
Find elsewhere
🌐
DEV Community
dev.to › sanspanic › the-javascript-reduce-method-3j8l
The JavaScript Reduce Method - DEV Community
July 23, 2021 - The initial value is an object with two properties, goodClimateBehaviours and badClimateBehaviours. This is our first accumulator. The callback reducer function iterates over the array of objects. Each time, it checks whether the current object has greenPoints greater than 0.
🌐
Redbitdev
redbitdev.com › post › using-array-reduce-with-objects
Using Array.reduce With Objects
September 21, 2021 - Example 7 creates a new object containing the properties from 'obj2' overridden by the properties from 'obj1'. Therefore, the values from 'obj2' serve as fallback or defaults for the values from 'obj1'. Notice that the result retains the 'null' and empty string values from 'obj1'. That happens because 'null' and an empty string are both defined values. We probably didn't want this result but 'Array.reduce' offers a solution.
🌐
Stephan Miller
stephanmiller.com › javascript-reduce
JavaScript Reduce - A Complete Guide to the Only JS Array Function You Really Need — Stephan Miller
January 11, 2024 - JavaScript reduce is a higher order JavaScript function used for manipulating data that reduces an array to a single value. But what this definition doesn’t tell you is that this “single value” can be anything: number, string, array, or object. And that definition is what kept me from using it for a long time unless I needed to do something like get the sum of ...
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript
JavaScript | MDN
1 month ago - Explanation of the widely misunderstood and underestimated prototype-based inheritance. ... Memory life cycle and garbage collection in JavaScript. Browse the complete JavaScript reference documentation. ... Get to know standard built-in objects: Array, Boolean, Error, Function, JSON, Math, Number, Object, RegExp, String, Map, Set, WeakMap, WeakSet, and others.
🌐
Refactoring.Guru
refactoring.guru › home › design patterns › creational patterns
Prototype
January 1, 2026 - To reduce the duplication, you create several subclasses and put every common configuration code into their constructors. You solved the duplication problem, but now you have lots of dummy subclasses. The Prototype pattern lets you use a set of pre-built objects configured in various ways as prototypes.
🌐
npm
npmjs.com › package › xlsx
xlsx - npm
With the header: 1 option, the function exports an array of arrays of values. ... x-spreadsheet is an interactive data grid for previewing and modifying structured data in the web browser. The xspreadsheet demo includes a sample script with the stox function for converting from a workbook to x-spreadsheet data object.
      » npm install xlsx
    
Published   Mar 24, 2022
Version   0.18.5
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Reduce array of nested objects? - JavaScript - The freeCodeCamp Forum
January 19, 2021 - Hey guys, got this array of objects that I want to reduce the quantity of each item to a single summed up value. What is the most efficient way of achieving this? cartItems.reduce() is definitely what I’m wanting, but ho…
🌐
US EPA
epa.gov › indoor-air-quality-iaq › volatile-organic-compounds-impact-indoor-air-quality
Volatile Organic Compounds' Impact on Indoor Air Quality | US EPA
July 24, 2025 - Formaldehyde, one of the best known VOCs, is one of the few indoor air pollutants that can be readily measured. Identify, and if possible, remove the source. If not possible to remove, reduce exposure by using a sealant on all exposed surfaces of paneling and other furnishings.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Spread_syntax
Spread syntax (...) - JavaScript | MDN
1 month ago - In the above example, the spread syntax does not work as one might expect: it spreads an array of arguments into the object literal, due to the rest parameter. Here is an implementation of merge using the spread syntax, whose behavior is similar to Object.assign(), except that it doesn't trigger setters, nor mutates any object: ... const obj1 = { foo: "bar", x: 42 }; const obj2 = { foo: "baz", y: 13 }; const merge = (...objects) => objects.reduce((acc, cur) => ({ ...acc, ...cur })); const mergedObj = merge(obj1, obj2); // { foo: 'baz', x: 42, y: 13 }
🌐
Simplilearn
simplilearn.com › home › resources › software development › javascript tutorial: learn javascript from scratch › javascript array reduce(): explained with syntax and examples
JavaScript Array Reduce(): Explained With Syntax and Examples | Simplilearn
July 16, 2024 - Learn everything about JavaScript array reduce and how you can use this method to reduce an array to a single value. Explained with syntax and examples.
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
Embarcadero
blogs.embarcadero.com › five-open-source-delphi-libraries-for-ai-applications
Five Open-Source Delphi Libraries for AI Applications – Embarcadero RAD Studio, Delphi, & C++Builder Blogs
February 27, 2026 - Arrays of objects with identical keys become CSV-style tables. Repeated structure gets folded. Unnecessary syntax disappears. ... The library implements the TOON v2.0 specification with 340+ conformance tests. It auto-detects tabular arrays, handles nested objects, and degrades gracefully when data doesn’t fit the compact format. In our production environment, Toon4D reduces prompt sizes by 30-60%, which translates directly to lower API costs and faster response times.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › filter
Array.prototype.filter() - JavaScript | MDN
The filter() method of Array instances creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
🌐
Telerik
telerik.com › blogs › understanding-javascript-array-reduce
Understanding JavaScript’s Array Reduce
April 23, 2021 - Imagine you have a bag where you store your marbles, say const marbles = []. At first your bag is empty, but you want to store some marbles in it, so you marbles.push(3) some marbles into it. This bag has many pockets inside of it, so after adding some marbles and looking inside you see [3, 5, 1]. The objective is now to find a way to count them. We want to reduce this whole bag (array) into a single value—a count of our marbles.
🌐
Todoist
developer.todoist.com › api › v1
Todoist API
Batching: reading and writing of multiple resources can be done in a single HTTP request. Batch requests help clients reduce the number of network calls needed to sync resources.