Array Filter Method
filter() tests each element of an array with a function and returns a new array holding only the elements that passed. The callback returns true to keep an element and false to leave it out. The original array is not changed.
const temperatures = [12, 21, 18, 25, 9, 23];
const warmDays = temperatures.filter((temperature) => temperature > 20);
console.log(warmDays);console.log(temperatures);This prints:
[ 21, 25, 23 ][ 12, 21, 18, 25, 9, 23 ]Filtering objects
Section titled “Filtering objects”With an array of objects, the test usually reads a property. The new array holds the same objects as the original, not copies, so changing one through the filtered array changes it in the original as well.
const todos = [ { text: 'Water the plants', done: true }, { text: 'Pay the gas bill', done: false }, { text: 'Return library books', done: false },];
const outstanding = todos.filter((todo) => !todo.done);console.log(outstanding);
outstanding[0].done = true;console.log(todos[1]);This prints:
[ { text: 'Pay the gas bill', done: false }, { text: 'Return library books', done: false }]{ text: 'Pay the gas bill', done: true }Truthy results and empty results
Section titled “Truthy results and empty results”The callback’s return value does not have to be a Boolean. filter() keeps the element when the value is truthy, so passing Boolean as the callback removes empty strings, null, undefined, 0 and NaN in one step. When nothing passes the test, filter() returns an empty array rather than undefined, so code that loops over the result still works.
const answers = ['yes', '', 'no', null, 'maybe', undefined, 0];
console.log(answers.filter(Boolean));console.log(answers.filter((answer) => answer === 'never'));This prints:
[ 'yes', 'no', 'maybe' ][]Steve Griffith covers this topic in his video JavaScript Array filter method.