The built-in array function filter will help you filter out the unwanted elements from the array and return a new array consisting only of suitable items.

To work correctly, the filter function accepts a parameter called “filtering function” or “filtering predicate”. This “filtering function” takes a single element of the array and returns true if the element passes the filter, otherwise it should return false.

Let’s rewrite the previous example using the filter function:

const arr = [ -1, 2, 4, 0, -5, 7 ];
const greaterThanZero = item => item > 0;

const positives = arr.filter(greaterThanZero);

console.log(positives); // [ 2, 4, 7 ]

This is not the shortest option, however. I created the greaterThanZero function just to emphasize that the filter function takes another function as a parameter.

In practice, for simple filters, you will more often see an anonymous filtering function written right inside the filter brackets.

const arr = [ -1, 2, 4, 0, -5, 7 ];

const positives = arr.filter(item => item > 0);

console.log(positives); // [ 2, 4, 7 ]

— Can I ask a stupid question?

— Sure.

— What happens if my “filtering function” always returns false?

— If the function that you use in Array.filter always returns false, then you’ll get an empty array as an output.

const arr = [ -1, 2, 4, 0, -5, 7 ];

const positives = arr.filter(item => false);

console.log(positives); // []
console.log(arr); // [ -1, 2, 4, 0, -5, 7 ]

Note that you will get a new empty array, and the original arr array will not change in any way.

— And if I choose to always return true, then I will get a copy of the input array?

— Right. But it’s like hammering nails with a microscope, so I do not recommend using the filter method for copying arrays.

With filter, you can also work with an array of objects. For example, you might want to filter all users over 18 years of age.

const users = [
  {name: 'Jake', age: 15},
  {name: 'John', age: 16},
  {name: 'Jill', age: 25},
  {name: 'Bill', age: 82},
];

const grownUps = users.filter(user => user.age > 18);

console.log(grownUps); // [ { name: 'Jill', age: 25 }, { name: 'Bill', age: 82 } ]