Pass parameter in FILTER of a Javascript array

Asked

Viewed 658 times

0

I need to pass a parameter to an external function I want to create for a filter array, but do not know how to do. 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 doesn’t work because I can’t get through qParam by parameter and this variable is also outside the scope accessible by myFunction. How do I fix it:

function myFunction(value, qParam) {
    return value === qParam;
}
const user = myArray.filter(myFunction);

1 answer

2


What you can do is use the concept of decorator, which simplistically is a function that returns another function, applying some treatment on this. In this case, the decorator would receive the parameter name and return a function that performs the name filter relative to the value of name:

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

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

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

Take 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);

  • Perfect. Thank you! I am using this code in Node.js and tried to write the functions in the format "Arrow Function", but it did not work no... will not work even for the internal function, the filter within the filterByName?

  • I can’t say for sure. You’ve made a mistake?

  • returns Undefined... as Arrow Function simply is not recognized. At least the way I wrote.

  • @wBB I tested on Repl.it and it worked perfectly. Check if you have put the correct syntax.

  • The one I sent on the link in the last comment. You saw?

  • Sorry Anderson... I had not noticed that you put the link associated with your reply and did not have time to delete my comment, because you have already posted another reply. It’s too fast on the trigger! But it worked OK your solution. I was sure that the function filterByName had to have its name spelled out to be external (without being Arrow), so I just did the internal function like Arrow Function and so it was going wrong. Thank you!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.