The JavaScript Array `filter()` Method

Jul 1, 2020

The Array#filter() function in JavaScript returns a new array with all the elements from the original array that the given callback returns truthy for.

For example, given an array of numbers 1-10, below is how you can use filter() to return an array of even numbers.

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

nums.filter(function isEven(num) {
  return num % 2 === 0;
}); // [2, 4, 6, 8, 10]

The filter() function returns a new array whose elements are the elements of nums for which isEven() returned true.

The index Argument

JavaScript calls the filter() callback with 3 arguments. The first argument is the element in the array, and the 2nd argument is the index in the array.

For example, below is how you can get an array with only the odd indexes of the original array:

const names = [
  'James',
  'John',
  'Robert',
  'Michael',
  'William'
];

names.filter(function isOddIndex(el, index) {
  return index % 2 === 1;
}); // ['John', 'Michael']

More Fundamentals Tutorials