1

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"

1 Answer 1

5

The filter line has essentially added another loop. It should be

names = searchWords.filter(x => students.indexOf(x) !== -1);
Sign up to request clarification or add additional context in comments.

3 Comments

I was just answering that… ;-)
Wow javascript has changed since I last used it. Now we have let and lambda functions. Cool.
@0x499602D2—it always had lambda functions, the arrow syntax is new though (it sets this lexically rather than in the call).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.