Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is reduce function outputting no of items in an array?

I'm learning ES6 from a tutorial and while playing with the code, I found something that I didn't understand. The code below outputs '3'.

var primaryColors = [

  { color: 'red' },
  { color: 'yellow' },
  { color: 'blue' },

];

var newColors = [];

primaryColors.reduce(function(color, primaryColor){

  return newColors.push(primaryColor.color);

}, []);

Why is the return statement returning the no of data in the "stack"?

like image 638
Bikal Nepal Avatar asked Dec 13 '22 16:12

Bikal Nepal


1 Answers

Why is reduce function outputting no of items in an array?

As Nenad Vracar said, because push returns the number of items in the array, and reduce returns the last value the callback returned.

reduce is not the right tool for this job. map is:

var newColors = primaryColors.map(function(primaryColor) {
    return primaryColor.color;
});

var primaryColors = [
  { color: 'red' },
  { color: 'yellow' },
  { color: 'blue' },
];
var newColors = primaryColors.map(function(primaryColor) {
    return primaryColor.color;
});
console.log(newColors);

or with an ES2015 arrow function:

var newColors = primaryColors.map(primaryColor => primaryColor.color);

var primaryColors = [
  { color: 'red' },
  { color: 'yellow' },
  { color: 'blue' },
];
var newColors = primaryColors.map(primaryColor => primaryColor.color);
console.log(newColors);

and if we're doing ES2015, we can throw in destructuring:

var newColors = primaryColors.map(({color}) => color);

var primaryColors = [
  { color: 'red' },
  { color: 'yellow' },
  { color: 'blue' },
];
var newColors = primaryColors.map(({color}) => color);
console.log(newColors);
like image 53
T.J. Crowder Avatar answered Dec 16 '22 05:12

T.J. Crowder