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.

JavaScript

Advertisement

Answer

You could simplify the two functions into one.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement