Reputation: 6029
This javascript code tries to use the array.filter
for better performance instead of the for loop "I guess". Any way, the results are not the same, when it was expected to be.
It tries to find out the names of students
who are included in the searchWords
array.
Any ideas why?thx
let searchWords = ['john','matt','marry'];
let students = ['matt','jack'];
let names = [];
for (let i = 0; i < searchWords.length; i++) {
if (students.indexOf(searchWords[i]) !== -1) {
names.push(searchWords[i]);
}
}
console.log(names.length); // => 1 "correct"
names = [];
names = searchWords.filter(x => students.filter(y => students.indexOf(x) !== -1));
console.log(names.length); // => 3 "incorrect"
Upvotes: 1
Views: 291
Reputation: 81
The filter line has essentially added another loop. It should be
names = searchWords.filter(x => students.indexOf(x) !== -1);
Upvotes: 5