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
x
16
16
1
//loop to get random names with one person named "John Smith"
2
var fullNames = (getNames = () => {
3
let names = [];
4
for (let i = 0; i < 9; i++) {
5
names.push(`Human${i} Person${i}`);
6
}
7
names.push("John Smith");
8
return names;
9
})();
10
11
var filterFirstName = (fullName, nameQuery) =>
12
fullName.split(" ")[0] === nameQuery;
13
14
var searchFirstNames = (namesAr, nameQuery) =>
15
namesAr.filter(filterFirstName)(fullNames, "John");
16
Advertisement
Answer
You could simplify the two functions into one.
JavaScript
1
14
14
1
//loop to get random names with one person named "John Smith"
2
var fullNames = (getNames = () => {
3
let names = [];
4
for (let i = 0; i < 9; i++) {
5
names.push(`Human${i} Person${i}`);
6
}
7
names.push("John Smith");
8
return names;
9
})();
10
11
var searchFirstNames = (namesAr, nameQuery) => namesAr.filter(person => person.split(" ")[0] === nameQuery)
12
13
searchFirstNames(fullNames, "John")
14