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"?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With