Why is this simple example of plain Javascript reduce not working?
// expected output: ["red", "yellow", "blue"]
var primaryColors = [
{ color: 'red' },
{ color: 'yellow' },
{ color: 'blue' }
];
primaryColors.reduce({
function(previous, primaryColor) {
previous.push(primaryColor.color);
return previous;
}
}, []);
// VM607:2 Uncaught TypeError: #<Object> is not a function
// at Array.reduce (native)
// at <anonymous>:2:15
As per the signature of reduce function the first parameter of it should be a function,
primaryColors.reduce(function(previous, primaryColor) {
previous.push(primaryColor.color);
return previous;
}, []);
Additionally, this scenario is a best fit for map,
var result = primaryColors.map(function(primaryColor) {
return primaryColor.color;
}, []);
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