Miha Šušteršič Miha Šušteršič - 16 days ago 6
Javascript Question

array.filter by object property, argument is not defined

I am trying to write a filter function that takes 2 parameter - id type and the actual id value. Then I want to filter an array of object by these ids. For instance here I am trying to get a new array that only includes values with the name of Mike.

object:

var sample = [
{ name: 'Mike'},
{ name: 'John'}
];


filter function:

function filterById(obj, parameter, id) {
return obj.parameter == id;
}


this:

console.log(sample.filter(filterById(name, 'Mike')));


returns name is not defined.

Do I need to pass in the actual array as well? Is it possible to pass parameters into filter functions at all?

Answer

You would need to pass the "parameter" as a string too, and use the square bracket notation, and for this all to work your filterById function would itself have to return a function which matches the function used by Array.prototype.filter:

var sample = [
  { name: 'Mike'},
  { name: 'John'}
];

function filterById(parameter, id) {
  return function(obj){
    return obj[parameter] == id;
  }
}

console.log(sample.filter(filterById('name', 'Mike')));

Comments