← All references

Array.filter()

array.filter(callback)

Keep only elements that pass a test.

Array.filter()

Returns a new array containing only elements for which the callback returns truthy.

``js\nconst nums = [1, 2, 3, 4, 5];\nconst evens = nums.filter(n => n % 2 === 0); // [2, 4]\nconst adults = users.filter(u => u.age >= 18);\n``

Example

const nums = [1, 2, 3, 4, 5, 6];\nconst evens = nums.filter(n => n % 2 === 0);\nconsole.log("Evens:", evens);\n\nconst words = ["cat", "elephant", "dog", "giraffe"];\nconst long = words.filter(w => w.length > 4);\nconsole.log("Long words:", long);