1

Given

var stuffs = [
    { id : 1, name : "orange"},
    { id : 2, name : "apple"}, 
    { id : 0, name:"grapes"}
];
var filterMethod1 = new function(o){return (o.id>=1);}; // this gives undefined error for o
function filterMethod2(o) {return (o.id>=1);};

Why is using anonymous function not working for array filter() method?

var temp = stuffs.filter(new function(o){ return (o.id>=1);}); // o is undefined if used this way

Using declared function works fine:

var temp = stuffs.filter(filterMethod2);
rustyengineer
  • 343
  • 3
  • 16

2 Answers2

4

You don't need to use new to create an anonymous function. The new keyword in Javascript is used to call a function as an object constructor, and the parameters are typically used by the constructor to initialize properties of the object. Just put the anonymous function in the argument to filter().:

var temp = stuffs.filter(function(o){ return (o.id>=1);});
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

Just get rid of the "new" keyword and it should work.

mikjay
  • 36
  • 3