Skip to content
Advertisement

How can I pass a variable to be used as the condition in a filter?

I am trying to filter an array of full names by a specific first name. I have created the filterFirstName function which accepts arguments for the name and the criteria to compare it to.

I then use that function in my filter. I looked up the syntax for filter callback(element[, index[, array]]. The element is the fullName but the nameQuery isn’t the index or array.

I passed the fullNames array and "John" string as my arguments in case it knew to use "John" as the nameQuery variable. That also received an error.

I could not find any guidance showing this scenario so I may need to be directed to a different approach.

     //loop to get random names with one person named "John Smith"  
     var fullNames = (getNames = () => {
        let names = [];
        for (let i = 0; i < 9; i++) {
          names.push(`Human${i} Person${i}`);
        }
        names.push("John Smith");
        return names;
      })();

      var filterFirstName = (fullName, nameQuery) =>
        fullName.split(" ")[0] === nameQuery;

      var searchFirstNames = (namesAr, nameQuery) =>
        namesAr.filter(filterFirstName)(fullNames, "John");

Advertisement

Answer

You could simplify the two functions into one.

   //loop to get random names with one person named "John Smith"  
   var fullNames = (getNames = () => {
      let names = [];
      for (let i = 0; i < 9; i++) {
        names.push(`Human${i} Person${i}`);
      }
      names.push("John Smith");
      return names;
    })();

    var searchFirstNames = (namesAr, nameQuery) => namesAr.filter(person => person.split(" ")[0] === nameQuery)

    searchFirstNames(fullNames, "John")
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement