Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 11, 2021 01:40 am GMT

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' ]

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

Syntax

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

  • functionfunction 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:

ArgumentsDescription
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 ]
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 ]

Notice:

0 and undefined are equal to false in JavaScript. 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.


Original Link: https://dev.to/sun00120/javascript-array-prototype-filter-12b9

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To