Lessons · JavaScript · filter
Keeping what passes
arr.filter(fn) returns a new array of the items for which fn returned something truthy. The original is untouched.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Active users, orders over a limit, rows matching a search: nearly every list on a page is a filtered version of a bigger one.
How to think about it
Write the test as a function that returns true to keep. Chain it with map when you also need to reshape the survivors. Expect an empty array, never undefined, when nothing passes.
Worked example
const nums = [1, 2, 3, 4];Four numbers.
const evens = nums.filter(n => n % 2 === 0);Keep the even ones.
console.log(evens, nums);[ 2, 4 ] [ 1, 2, 3, 4 ]: a new array of what passed; the original untouched.
console.log(nums.filter(n => n > 10));[]: nothing passed, and that is an empty array.
Your turn
Only the adults.
const adults = people.(p => p.age >= 18);
Solve one with the tests running
The trap
filter keeps items where the function returns anything truthy. Return a string by mistake and everything is kept.
Practise filter on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.