JavaScript Arrays: Filter
Welcome to the Filter lesson!
JavaScript arrays' `.filter` returns a new array containing only the elements where the function returns `true`.
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
We often need to iterate through an array and pick out elements that meet some condition. In the next example, we have an array of users. We want to build an array of every user who is an admin. One possible solution is a
forloop.>
const users = [{name: 'Amir', admin: true},{name: 'Betty', admin: false},];const admins = [];for (let i=0; i<users.length; i++) {const user = users[i];if (user.admin) {admins.push(user);}}admins.map(user => user.name);Result:
['Amir']
That loop is easy enough to read, but we can use the built-in
.filtermethod to get the same result with much less code..filtertakes a callback function and calls it with each element in an array. If the function returnstrue, then.filterkeeps that element. Otherwise, it discards the element.>
const users = [{name: 'Amir', admin: true},{name: 'Betty', admin: false},];const admins = users.filter(user => user.admin);admins.map(user => user.name);Result:
['Amir']
>
const arrays = [[1, 2],[2, 3],[3, 4],];arrays.filter(array => array.includes(2));Result:
[[1, 2], [2, 3]]
.filterbuilds and returns a new array. The original array isn't changed.>
const users = [{name: 'Amir', admin: true},{name: 'Betty', admin: false},];users.filter(user => user.admin);users.map(user => user.name);Result:
['Amir', 'Betty']
JavaScript provides
.filterfor us, but it's simple to implement. We could use aforloop to iterate through the array, passing each element into the callback function.>
function filter(array, callback) {const results = [];for (let i=0; i<array.length; i++) {if (callback(array[i])) {results.push(array[i]);}}return results;}filter([1, 2, 3], x => x !== 2);Result:
[1, 3]