When would you use filter, find, some and every on an array?
filter returns all matches as an array, find returns the first match or undefined, some says whether at least one matches, and every says whether all match. some and every stop as soon as the answer is known.
Explain it simply
Think of a class result sheet with marks.
- filter: "give me everyone who passed" returns a new array, possibly empty.
- find: "give me the first student who passed" returns one item, or
undefined. - some: "did anyone fail?" returns true or false.
- every: "did everyone pass?" returns true or false.
findIndex is the sibling of find that returns the position, or -1. Picking the right one avoids writing a loop with a flag variable.
Example
const marks = [35, 72, 90, 48];
console.log(marks.filter((m) => m >= 40)); // Output: [72,90,48]
console.log(marks.find((m) => m >= 40)); // Output: 72
console.log(marks.findIndex((m) => m > 80)); // Output: 2
console.log(marks.some((m) => m < 40)); // Output: true
console.log(marks.every((m) => m >= 35)); // Output: true
console.log(String(marks.find((m) => m > 100))); // Output: undefinedWhat to say in the interview
"filter gives all matches as a new array, find gives the first match or undefined, some answers 'is there at least one', every answers 'do all pass'. some and every short-circuit. I choose the one that matches the question instead of looping manually."
Common mistakes
- Using filter(...)[0] when find does the job and stops early.
- Checking if (array.filter(...)) for existence. An empty array is truthy; use some or check length.