filter method

The filter method allows you to filter the elements of an array, leaving only elements that match a certain condition. The method in the parameter receives a function that will be executed for each element of the array. As its result, the method returns a new array, which will include only those elements for which the passed function returns true.

You can pass three parameters to a function. If these parameters are present (they are not required), then the first one will automatically get the array element, the second one will get its number in the array (index), and the third one will get the array itself.

Syntax

javascriptlet new array = array.filter(function(element, index, array) {
  some code
  return true or false
});

Example

Let's filter an array, leaving only positive numbers in it:

javascriptlet arr = [-2, 5, 1, -5, -1, 1, 3, 4, -1];

let res = arr.filter(function(elem) {
  if (elem >= 0) {
    return true;
  } else {
    return false;
  }
});

console.log(res);

The code execution result:

javascript[5, 1, 1, 3, 4]

Example

We shorten a code using arrow function:

javascriptlet arr = [-2, 5, 1, -5, -1, 1, 3, 4, -1];

let res = arr.filter(elem => {
  if (elem >= 0) {
    return true;
  } else {
    return false;
  }
});

console.log(res);

The code execution result:

javascript[5, 1, 1, 3, 4]

Example

Let's shorten a code using shorthand for logical operations:

javascriptlet arr = [-2, 5, 1, -5, -1, 1, 3, 4, -1];

let res = arr.filter(elem => {
  return elem >= 0;
});

console.log(res);

The code execution result:

javascript[5, 1, 1, 3, 4]

Example

Let's shorten a code using the features of arrow functions:

javascriptlet arr = [-2, 5, 1, -5, -1, 1, 3, 4, -1];
let res = arr.filter(elem => elem > 0);

console.log(res);

The code execution result:

javascript[5, 1, 1, 3, 4]

Example

If necessary, an array itself can be passed to the third parameter:

javascriptlet res = arr.filter(function(elem, index, arr) {
  array arr will be available here
});

See also

  • the map and forEach methods
    that allow you to apply a function to each element of an array
  • the some and every methods
    that perform an array check
  • the reduce and reduceRight methods
    that reduce an array to a single value