So how do we use the
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' ]
.filter() after the array wants to be filtered.
array.filter(functionName(currentValue, index, arr), thisValue)
functionis 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
falsewhich did not pass the test, it won't add the element to the new array.
|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.|
- The value
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.
filter()doesn't change the original array.
filter()doesn't work with the function for the empty array.
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 ]
0 and undefined are equal to false. Therefore, it won't be printed out.
Here is a very helpful youtube channel created by Steve.