Skip to content

Instantly share code, notes, and snippets.

@msonnabaum
Created November 10, 2015 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msonnabaum/f83ac59771ef7a219c40 to your computer and use it in GitHub Desktop.
Save msonnabaum/f83ac59771ef7a219c40 to your computer and use it in GitHub Desktop.
[1,2,3].reduce(function(memo, current) {
console.log(memo);
}, {});
// > {}
// > undefined
// > undefined
@mikeyp
Copy link

mikeyp commented Nov 10, 2015

memo is based on the return value which is empty, try

[1,2,3].reduce(function(memo, current) {
  console.log(memo);
  return memo;
}, {});

@Thiruppathi
Copy link

When using reduce follow the 2 rules.

  1. Always pass an initialValue
  2. Always return the accumulator
var data = [1,2,3];
var initialValue = 0;
var reducer = function(accumulator, item) {
  return accumulator + item;
};
var total = data.reduce(reducer, initialValue);
console.log('Sum of the array', data, 'is: ', total);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment