Trying to enhance performance, this snippet of JavaScript code employs the array.filter
instead of a traditional for loop. Surprisingly, the expected results are not achieved as intended. The purpose is to identify the names of students that match those in the searchWords array.
Any thoughts on why this is happening? Thank you.
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"