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
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › reduce
Array.prototype.reduce() - JavaScript | MDN
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.
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.

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.
Reduce takes two arguments - a ... in the array as reduce iterates over it (this is sometimes called the · reducer), and an initial value for the thing you are building (sometimes called the · accumulator - because it accumulates or builds up into something by the end of the iteration). The thing you are building can by any data type - an object, number, array, ... 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
javascript - Reduce array of objects into object of arrays - Code Review Stack Exchange
I have an array of objects where each object has two keys: key (k) and value (v). I need to make an object that would take values of k and collect corresponding values of v as a value of this key, an More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
December 3, 2015
🌐
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
Array[ ] Array( ) at() concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() findLast() findLastIndex() flat() flatMap() forEach() from() includes() indexOf() isArray() join() keys() lastIndexOf() length map() of() pop() prototype push() reduce() reduceRight() rest (...) reverse() shift() slice() some() sort() splice() spread (...) toReversed() toSorted() toSpliced() toString() unshift() values() valueOf() with() JS Boolean · Boolean() new Boolean() constructor prototype toString() valueOf() JS Classes · constructor() extends static super JS Constructors · Array() Date() Error() Function() Map() Object() Promise() RegExp() Set() String() JS Dates ·
🌐
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
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 - Our initial value is an empty object ({}) and it gets built up using these two arrays. But we only have to use reduce on one and then we can use the index of the current value in that array to get the value of the element with the same index in the other array to create the object.
🌐
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 how would I be able to destructure this in the parameters?
🌐
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
🌐
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 }
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › filter
Array.prototype.filter() - JavaScript | MDN
December 13, 2025 - 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.
🌐
W3Schools
w3schools.com › jsref › jsref_obj_array.asp
JavaScript Array Reference
Array[ ] Array( ) at() concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() findLast() findLastIndex() flat() flatMap() forEach() from() includes() indexOf() isArray() join() keys() lastIndexOf() length map() of() pop() prototype push() reduce() reduceRight() rest (...) reverse() shift() slice() some() sort() splice() spread (...) toReversed() toSorted() toSpliced() toString() unshift() values() valueOf() with() JS Boolean · Boolean() new Boolean() constructor prototype toString() valueOf() JS Classes · constructor() extends static super JS Constructors · Array() Date() Error() Function() Map() Object() Promise() RegExp() Set() String() JS Dates ·
🌐
CodeBurst
codeburst.io › how-to-reduce-array-to-a-single-type-11cfe2bcae66
How to Reduce Javascript Arrays With array.reduce() | codeburst
November 6, 2020 - This example reduces an array of ... confusing at first glance, the logic is simple: reduce an array to a single value by iterating through the array using a callback function....
🌐
egghead.io
egghead.io › lessons › javascript-reduce-an-array-into-a-single-object
Reduce an Array into a Single Object | egghead.io
[03:33] We're going to step through ... whole thing evaluates to the value that gets returned from the very last call of the Reduce function....
Published   October 13, 2015
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › data types
Array methods
That’s natural, because delete obj.key removes a value by the key. It’s all it does. Fine for objects. But for arrays we usually want the rest of the elements to shift and occupy the freed place.
🌐
Stackademic
blog.stackademic.com › returning-arrays-and-objects-from-the-reduce-method-006f899ba4bb
Returning Arrays and Objects from the reduce() Method | by Femi Majek | Stackademic
December 10, 2023 - In our reduce() method we then set a condition that pushes the current element in the iteration into our accumulator array(acc) only if it’s greater or equal to “18” and also explicitly return our accumulator(because in a function body, ...