Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript reduce example

Tags:

javascript

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
like image 266
StandardNerd Avatar asked Jul 15 '26 06:07

StandardNerd


1 Answers

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;
}, []); 

DEMO

Additionally, this scenario is a best fit for map,

var result = primaryColors.map(function(primaryColor) {
  return primaryColor.color;
}, []);

DEMO

like image 169
Rajaprabhu Aravindasamy Avatar answered Jul 20 '26 19:07

Rajaprabhu Aravindasamy