Array.prototype.filter
- Version
- es2025
- Review
- Draft
Summary#
Array.prototype.filter creates a new array containing only the elements that pass a predicate. The surviving elements stay in their original order.
Syntax#
const matching = array.filter((value, index, source) => keep(value));
Example#
const stock = [0, 7, 2, 0, 4];
const available = stock.filter((quantity) => quantity > 0);
console.log(JSON.stringify(available));
console.log(stock.length);
Expected output#
[7,2,4]
5
Common mistakes#
The predicate's return value selects the original element by truthiness. It cannot replace the element in the result. Use map afterwards when you also need to transform the values. The predicate visits only indices that exist on the array or its prototype.
Version applicability#
Array.prototype.filter is available from ECMAScript 5 onward. The syntax and example use ES2015 const and arrow functions.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0