Skip to content
On this page

Filter

filter is a commonly used operation that filters out certain elements from an Array and returns the remaining elements. Like map(), Array.prototype.filter() also accepts a function. However, unlike map(), filter() applies the passed function to each element and retains or discards the element based on whether the return value is true or false.

For example, to remove even numbers and keep only odd numbers in an Array, you can write:

javascript
let arr = [1, 2, 4, 5, 6, 9, 10, 15];
let r = arr.filter(function (x) {
    return x % 2 !== 0;
});
r; // [1, 5, 9, 15]

To remove empty strings from an Array, you can write:

javascript
let arr = ['A', '', 'B', null, undefined, 'C', '  '];
let r = arr.filter(function (s) {
    return s && s.trim(); // Note: trim() is not available in IE9 and earlier
});
r; // ['A', 'B', 'C']

The key to using filter() effectively lies in implementing a proper "filtering" function.

Callback Function

The callback function received by filter() can actually have multiple parameters. Typically, we only use the first parameter, which represents an element of the Array. The callback function can also take two additional parameters for the element's position and the array itself:

javascript
let arr = ['A', 'B', 'C'];
let r = arr.filter(function (element, index, self) {
    console.log(element); // Prints 'A', 'B', 'C' in order
    console.log(index); // Prints 0, 1, 2 in order
    console.log(self); // 'self' refers to the variable arr
    return true;
});

Using filter, you can cleverly remove duplicate elements from an Array:

javascript
let r,
    arr = ['apple', 'strawberry', 'banana', 'pear', 'apple', 'orange', 'orange', 'strawberry'];

r = arr.filter(function (element, index, self) {
    return self.indexOf(element) === index;
});

console.log(r);

The removal of duplicate elements relies on indexOf always returning the position of the first occurrence, so subsequent duplicate elements are filtered out since their positions differ.

Exercise

Try to use filter() to extract prime numbers:

javascript
function get_primes(arr) {
    // FIXME:
    return [];
}

// Test:
let x,
    r,
    arr = [];
for (x = 1; x < 100; x++) {
    arr.push(x);
}
r = get_primes(arr);
if (r.toString() === [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97].toString()) {
    console.log('Test passed!');
} else {
    console.log('Test failed: ' + r.toString());
}
Filter has loaded