Execute Program

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 for loop.

  • >
    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']Pass Icon
  • That loop is easy enough to read, but we can use the built-in .filter method to get the same result with much less code.

  • .filter takes a callback function and calls it with each element in an array. If the function returns true, then .filter keeps 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']Pass Icon
  • >
    const arrays = [
    [1, 2],
    [2, 3],
    [3, 4],
    ];
    arrays.filter(array => array.includes(2));
    Result:
    [[1, 2], [2, 3]]Pass Icon
  • .filter builds 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']Pass Icon
  • JavaScript provides .filter for us, but it's simple to implement. We could use a for loop 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]Pass Icon