iteration
Array.prototype.filter
Creates a new array containing every element for which the callback returned a truthy value. Reach for it to pare a list down to items matching a predicate.
arr.filter(callbackFn[, thisArg]) Parameters
| Parameter | Purpose |
|---|---|
| callbackFn(element, index, array) | Predicate — return truthy to keep the element |
| thisArg | Value used as `this` inside callbackFn |
Examples
console.log([1,2,3,4].filter(n => n % 2 === 0)); Logs: [2, 4]
console.log(['a','','b',null,'c'].filter(Boolean)); Logs: ['a', 'b', 'c'] (drops falsy)
const users = [{age:12},{age:30},{age:8}]; console.log(users.filter(u => u.age >= 18)); Logs: [{age: 30}]
console.log([1,2,3].filter(n => n > 99)); Logs: [] (no match returns empty array, not undefined)
Gotcha
Always returns a new array (never null/undefined) — check `.length` not truthiness on the result. Truthy/falsy rules apply: 0, '', null, undefined, NaN are all dropped by `filter(Boolean)`.
Related methods
Array.prototype.map
Creates a new array populated with the results of calling a callback on every element of the calling array. Reach for it whenever you want to transform each element 1-to-1 into a new value.
Array.prototype.find
Returns the first element for which the callback returns truthy, or undefined if none match. Reach for it when you need the matching item itself, not just its index.
Array.prototype.reduce
Runs a reducer function on each element, left-to-right, folding the array into a single accumulated value. Reach for it to sum/product/group/build an object or any custom fold.
Array.prototype.forEach
Executes a provided callback once for each array element, in ascending order. Reach for it when you need side effects (logging, DOM updates, pushing to another store) and do not need a return value.
Array.prototype.some
Returns true if the callback returns truthy for at least one element, short-circuiting on the first hit. Reach for it to answer "does anything match?" without walking the full array.