DEV Community

Cover image for JavaScript -Array.prototype.filter()
Jasper Sun
Jasper Sun

Posted on • Updated on

JavaScript -Array.prototype.filter()

Array.filter()

JavaScript is one of the most important parts of web development. Today we are taking a look at the filter() method in JavaScript.

So how do we use the filter() method?

Here is a simply example:

const fruits = ["fig", "pear", "apple", "banana", "blueberry", "watermelon"];

const fruit = fruits.filter((name) => name.length >= 6);

console.log(fruit);

// find out fruit name that has six or more letters
//expected output: [ 'banana', 'blueberry', 'watermelon' ]
Enter fullscreen mode Exit fullscreen mode

Simply add .filter() after the array wants to be filtered.

Syntax

array.filter(functionName(currentValue, index, arr), thisValue)

  • function function is used to test each element in the array by pass or not. If it is true, it will keep the element and build a new array. If it is false which did not pass the test, it won't add the element to the new array.

The function has 3 arguments:

Arguments Description
Value/element <required> The element(s) now processed in the array.
Index <optional> The index of element(s) now processed in the array.
Array <optional> The array filter now processed.

thisValue <optional>

  • The value this when executing callback.

Notice:

  • The filter() will return a new array, only elements that pass the test will add to the new array. If no elements pass the test, it still will return an empty array.
  • The filter() doesn't change the original array.
  • The filter() doesn't work with the function for the empty array.

More examples

const age = [1, 6, 7, 13, 24, 36, 57, 61, 68, 79, 93];

const checkAge = age.filter((check) => check >= 50);

console.log(checkAge);

//find age in the array that 50 years and older
//expected output: [ 57, 61, 68, 79, 93 ]
Enter fullscreen mode Exit fullscreen mode
const number = [-9, -2, -1, 0, undefined, 3, 9, 12, 15];

const overZero = number.filter((num) => num > 0);

console.log(overZero);
// find the number in an array that is over 0.
//expected output: [ 3, 9, 12, 15 ]

const un = number.filter((num) => num);

console.log(un);

// find all numbers that is a number.
//expected output: [ -9, -2, -1, 3, 9, 12, 15 ]
Enter fullscreen mode Exit fullscreen mode

Notice:

0 and undefined are equal to false. Therefore, it won't be printed out.

If you want to learn more about the filter method or even more about JavaScript.
Here is a very helpful youtube channel created by Steve.

Discussion (0)