How come the reduce function is outputting the number of items in an array?
According to Nenad Vracar's explanation, this happens because the push
method returns the number of items in the array, while the reduce
method returns the last value that the callback function has returned.
Reduce
may not be the most suitable tool for this task. Consider using map
:
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);
You can also use 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);
If you're working with ES2015, you can also utilize destructuring:
var newColors = primaryColors.map(({color}) => color);
var primaryColors = [
{ color: 'red' },
{ color: 'yellow' },
{ color: 'blue' },
];
var newColors = primaryColors.map(({color}) => color);
console.log(newColors);