Passing parameter in the FILTER of an array in JavaScript

0

I need to pass a parameter to an external function that I want to create for a filter array, but I do not know how to do it. Example: This code already works:

const myArray = [
    { "name": "nome1" },
    { "name": "nome2" },
    { "name": "nome3" },
    { "name": "nome4" },
    { "name": "nome5" }
];

let qParam = myRequest.query.myParam;

// Retorna o item do array cujo campo "name" corresponde a "qParam"
const user = myArray.filter(u => qParam === u.name)[0];

Now I want to do something like this below, but it does not work because I can not pass qParam per parameter and this variable is also out of scope accessible by myFunction . How do I resolve this:

function myFunction(value, qParam) {
    return value === qParam;
}
const user = myArray.filter(myFunction);
    
asked by anonymous 26.05.2017 / 00:25

1 answer

2

What you can do is to use the concept of decorator, which in a simplistic way is a function that returns another function, applying some treatment on it. In this case, the decorator would get the parameter name and would return a function that filters the name against the value of name :

function filterByName(name) {
  return function filter(value) {
      return value.name === name;
  }
}

That is, to generate a filter that uses the value of qParam as a reference, just do:

const user = myArray.filter( filterByName(qParam) )[0];

See the example:

const myArray = [
    { "name": "nome1" },
    { "name": "nome2" },
    { "name": "nome3" },
    { "name": "nome4" },
    { "name": "nome5" }
];

let qParam = "nome3";

function filterByName(name) {
  return function filter(value) {
      return value.name === name;
  }
}

const user = myArray.filter(filterByName(qParam))[0];

console.log(user);
    
26.05.2017 / 01:39