[javascript] Javascript reduce on array of objects

Say I want to sum a.x for each element in arr.

arr = [{x:1},{x:2},{x:4}]
arr.reduce(function(a,b){return a.x + b.x})
>> NaN

I have cause to believe that a.x is undefined at some point.

The following works fine

arr = [1,2,4]
arr.reduce(function(a,b){return a + b})
>> 7

What am I doing wrong in the first example?

This question is related to javascript functional-programming node.js reduce

The answer is


to return a sum of all x props:

arr.reduce(
(a,b) => (a.x || a) + b.x 
)

At each step of your reduce, you aren't returning a new {x:???} object. So you either need to do:

arr = [{x:1},{x:2},{x:4}]
arr.reduce(function(a,b){return a + b.x})

or you need to do

arr = [{x:1},{x:2},{x:4}]
arr.reduce(function(a,b){return {x: a.x + b.x}; }) 

For the first iteration 'a' will be the first object in the array, hence a.x + b.x will return 1+2 i.e 3. Now in the next iteration the returned 3 is assigned to a, so a is a number now n calling a.x will give NaN.

Simple solution is first mapping the numbers in array and then reducing them as below:

arr.map(a=>a.x).reduce(function(a,b){return a+b})

here arr.map(a=>a.x) will provide an array of numbers [1,2,4] now using .reduce(function(a,b){return a+b}) will simple add these numbers without any hassel

Another simple solution is just to provide an initial sum as zero by assigning 0 to 'a' as below:

arr.reduce(function(a,b){return a + b.x},0)

reduce function iterates over a collection

arr = [{x:1},{x:2},{x:4}] // is a collection

arr.reduce(function(a,b){return a.x + b.x})

translates to:

arr.reduce(
    //for each index in the collection, this callback function is called
  function (
    a, //a = accumulator ,during each callback , value of accumulator is 
         passed inside the variable "a"
    b, //currentValue , for ex currentValue is {x:1} in 1st callback
    currentIndex,
    array
  ) {
    return a.x + b.x; 
  },
  accumulator // this is returned at the end of arr.reduce call 
    //accumulator = returned value i.e return a.x + b.x  in each callback. 
);

during each index callback, value of variable "accumulator" is passed into "a" parameter in the callback function. If we don't initialize "accumulator", its value will be undefined. Calling undefined.x would give you error.

To solve this, initialize "accumulator" with value 0 as Casey's answer showed above.

To understand the in-outs of "reduce" function, I would suggest you look at the source code of this function. Lodash library has reduce function which works exactly same as "reduce" function in ES6.

Here is the link : reduce source code


you should not use a.x for accumulator , Instead you can do like this `arr = [{x:1},{x:2},{x:4}]

arr.reduce(function(a,b){a + b.x},0)`


Others have answered this question, but I thought I'd toss in another approach. Rather than go directly to summing a.x, you can combine a map (from a.x to x) and reduce (to add the x's):

arr = [{x:1},{x:2},{x:4}]
arr.map(function(a) {return a.x;})
   .reduce(function(a,b) {return a + b;});

Admittedly, it's probably going to be slightly slower, but I thought it worth mentioning it as an option.


You can use reduce method as bellow; If you change the 0(zero) to 1 or other numbers, it will add it to total number. For example, this example gives the total number as 31 however if we change 0 to 1, total number will be 32.

const batteryBatches = [4, 5, 3, 4, 4, 6, 5];

let totalBatteries= batteryBatches.reduce((acc,val) => acc + val ,0)

Array reduce function takes three parameters i.e, initialValue(default it's 0) , accumulator and current value . By default the value of initialValue will be "0" . which is taken by accumulator

Let's see this in code .

var arr =[1,2,4] ;
arr.reduce((acc,currVal) => acc + currVal ) ; 
// (remember Initialvalue is 0 by default )

//first iteration** : 0 +1 => Now accumulator =1;
//second iteration** : 1 +2 => Now accumulator =3;
//third iteration** : 3 + 4 => Now accumulator = 7;
No more array properties now the loop breaks .
// solution = 7

Now same example with initial Value :

var initialValue = 10;
var arr =[1,2,4] ;
arr.reduce((acc,currVal) => acc + currVal,initialValue ) ; 
/
// (remember Initialvalue is 0 by default but now it's 10 )

//first iteration** : 10 +1 => Now accumulator =11;
//second iteration** : 11 +2 => Now accumulator =13;
//third iteration** : 13 + 4 => Now accumulator = 17;
No more array properties now the loop breaks .
//solution=17

Same applies for the object arrays as well(the current stackoverflow question) :

var arr = [{x:1},{x:2},{x:4}]
arr.reduce(function(acc,currVal){return acc + currVal.x}) 
// destructing {x:1} = currVal;
Now currVal is object which have all the object properties .So now 
currVal.x=>1 
//first iteration** : 0 +1 => Now accumulator =1;
//second iteration** : 1 +2 => Now accumulator =3;
//third iteration** : 3 + 4 => Now accumulator = 7;
No more array properties now the loop breaks 
//solution=7

ONE THING TO BARE IN MIND is InitialValue by default is 0 and can be given anything i mean {},[] and number


A cleaner way to accomplish this is by providing an initial value:

_x000D_
_x000D_
var arr = [{x:1}, {x:2}, {x:4}];_x000D_
arr.reduce(function (acc, obj) { return acc + obj.x; }, 0); // 7_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

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.


In the first step, it will work fine as the value of a will be 1 and that of b will be 2 but as 2+1 will be returned and in the next step the value of b will be the return value from step 1 i.e 3 and so b.x will be undefined...and undefined + anyNumber will be NaN and that is why you are getting that result.

Instead you can try this by giving initial value as zero i.e

arr.reduce(function(a,b){return a + b.x},0);


To formalize what has been pointed out, a reducer is a catamorphism which takes two arguments which may be the same type by coincidence, and returns a type which matches the first argument.

function reducer (accumulator: X, currentValue: Y): X { }

That means that the body of the reducer needs to be about converting currentValue and the current value of the accumulator to the value of the new accumulator.

This works in a straightforward way, when adding, because the accumulator and the element values both happen to be the same type (but serve different purposes).

[1, 2, 3].reduce((x, y) => x + y);

This just works because they're all numbers.

[{ age: 5 }, { age: 2 }, { age: 8 }]
  .reduce((total, thing) => total + thing.age, 0);

Now we're giving a starting value to the aggregator. The starting value should be the type that you expect the aggregator to be (the type you expect to come out as the final value), in the vast majority of cases. While you aren't forced to do this (and shouldn't be), it's important to keep in mind.

Once you know that, you can write meaningful reductions for other n:1 relationship problems.

Removing repeated words:

const skipIfAlreadyFound = (words, word) => words.includes(word)
    ? words
    : words.concat(word);

const deduplicatedWords = aBunchOfWords.reduce(skipIfAlreadyFound, []);

Providing a count of all words found:

const incrementWordCount = (counts, word) => {
  counts[word] = (counts[word] || 0) + 1;
  return counts;
};
const wordCounts = words.reduce(incrementWordCount, { });

Reducing an array of arrays, to a single flat array:

const concat = (a, b) => a.concat(b);

const numbers = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
].reduce(concat, []);

Any time you're looking to go from an array of things, to a single value that doesn't match a 1:1, reduce is something you might consider.

In fact, map and filter can both be implemented as reductions:

const map = (transform, array) =>
  array.reduce((list, el) => list.concat(transform(el)), []);

const filter = (predicate, array) => array.reduce(
  (list, el) => predicate(el) ? list.concat(el) : list,
  []
);

I hope this provides some further context for how to use reduce.

The one addition to this, which I haven't broken into yet, is when there is an expectation that the input and output types are specifically meant to be dynamic, because the array elements are functions:

const compose = (...fns) => x =>
  fns.reduceRight((x, f) => f(x), x);

const hgfx = h(g(f(x)));
const hgf = compose(h, g, f);
const hgfy = hgf(y);
const hgfz = hgf(z);

TL;DR, set the initial value

Using destructuring

arr.reduce( ( sum, { x } ) => sum + x , 0)

Without destructuring

arr.reduce( ( sum , cur ) => sum + cur.x , 0)

With Typescript

arr.reduce( ( sum, { x } : { x: number } ) => sum + x , 0)

Let's try the destructuring method:

_x000D_
_x000D_
const arr = [ { x: 1 }, { x: 2 }, { x: 4 } ]
const result = arr.reduce( ( sum, { x } ) => sum + x , 0)
console.log( result ) // 7
_x000D_
_x000D_
_x000D_

The key to this is setting initial value. The return value becomes first parameter of the next iteration.

Technique used in top answer is not idiomatic

The accepted answer proposes NOT passing the "optional" value. This is wrong, as the idiomatic way is that the second parameter always be included. Why? Three reasons:

1. Dangerous -- Not passing in the initial value is dangerous and can create side-effects and mutations if the callback function is careless.

Behold

const badCallback = (a,i) => Object.assign(a,i) 

const foo = [ { a: 1 }, { b: 2 }, { c: 3 } ]
const bar = foo.reduce( badCallback )  // bad use of Object.assign
// Look, we've tampered with the original array
foo //  [ { a: 1, b: 2, c: 3 }, { b: 2 }, { c: 3 } ]

If however we had done it this way, with the initial value:

const bar = foo.reduce( badCallback, {})
// foo is still OK
foo // { a: 1, b: 2, c: 3 }

For the record, unless you intend to mutate the original object, set the first parameter of Object.assign to an empty object. Like this: Object.assign({}, a, b, c).

2 - Better Type Inference --When using a tool like Typescript or an editor like VS Code, you get the benefit of telling the compiler the initial and it can catch errors if you're doing it wrong. If you don't set the initial value, in many situations it might not be able to guess and you could end up with creepy runtime errors.

3 - Respect the Functors -- JavaScript shines best when its inner functional child is unleashed. In the functional world, there is a standard on how you "fold" or reduce an array. When you fold or apply a catamorphism to the array, you take the values of that array to construct a new type. You need to communicate the resulting type--you should do this even if the final type is that of the values in the array, another array, or any other type.

Let's think about it another way. In JavaScript, functions can be pass around like data, this is how callbacks work, what is the result of the following code?

[1,2,3].reduce(callback)

Will it return an number? An object? This makes it clearer

[1,2,3].reduce(callback,0)

Read more on the functional programming spec here: https://github.com/fantasyland/fantasy-land#foldable

Some more background

The reduce method takes two parameters,

Array.prototype.reduce( callback, initialItem )

The callback function takes the following parameters

(accumulator, itemInArray, indexInArray, entireArray) => { /* do stuff */ }

For the first iteration,

  • If initialItem is provided, the reduce function passes the initialItem as the accumulator and the first item of the array as the itemInArray.

  • If initialItem is not provided, the reduce function passes the first item in the array as the initialItem and the second item in the array as itemInArray which can be confusing behavior.

I teach and recommend always setting the initial value of reduce.

You can check out the documentation at:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Hope this helps!


_x000D_
_x000D_
    _x000D_
  _x000D_
 //fill creates array with n element_x000D_
 //reduce requires 2 parameter , 3rd parameter as a length_x000D_
 var fibonacci = (n) => Array(n).fill().reduce((a, b, c) => {_x000D_
      return a.concat(c < 2 ? c : a[c - 1] + a[c - 2])_x000D_
  }, [])_x000D_
  console.log(fibonacci(8))
_x000D_
_x000D_
_x000D_


If you have a complex object with a lot of data, like an array of objects, you can take a step by step approach to solve this.

For e.g:

const myArray = [{ id: 1, value: 10}, { id: 2, value: 20}];

First, you should map your array into a new array of your interest, it could be a new array of values in this example.

const values = myArray.map(obj => obj.value);

This call back function will return a new array containing only values from the original array and store it on values const. Now your values const is an array like this:

values = [10, 20];

And now your are ready to perform your reduce:

const sum = values.reduce((accumulator, currentValue) => { return accumulator + currentValue; } , 0);

As you can see, the reduce method executes the call back function multiple times. For each time, it takes the current value of the item in the array and sum with the accumulator. So to properly sum it you need to set the initial value of your accumulator as the second argument of the reduce method.

Now you have your new const sum with the value of 30.


I did it in ES6 with a little improvement:

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

return number


You could use the map and reduce functions

const arr = [{x:1},{x:2},{x:4}];
const sum = arr.map(n => n.x).reduce((a, b) => a + b, 0);

I used to encounter this is my development, what I do is wrap my solution in a function to make it reusable in my environment, like this:

const sumArrayOfObject =(array, prop)=>array.reduce((sum, n)=>{return sum + n[prop]}, 0)

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to functional-programming

Dart: mapping a list (list.map) Index inside map() function functional way to iterate over range (ES6/7) How can I count occurrences with groupBy? How do I use the includes method in lodash to check if an object is in the collection? Does Java SE 8 have Pairs or Tuples? Functional style of Java 8's Optional.ifPresent and if-not-Present? What is difference between functional and imperative programming languages? How does functools partial do what it does? map function for objects (instead of arrays)

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to reduce

Javascript reduce() on Object How to use filter, map, and reduce in Python 3 What is the 'pythonic' equivalent to the 'fold' function from functional programming? Finding the average of a list NameError: name 'reduce' is not defined in Python Javascript reduce on array of objects