filter() method in JavaScript
Definition by MDN: The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Let's see some examples:
Example 1: Given an array of numbers, filter out all even numbers from the array?
const numbersArray = [1, 5, 22, 40, 3, 19, 6]
//Using arrow function
const newArray = numbersArray.filter(item => item % 2 === 0)
console.log(newArray)
Result: [22, 40, 6]
//Using normal function
function oddNumber(num){
if(num % 2 === 0){
return true
}
}
const newArray = numbersArray.filter(oddNumber)
console.log(newArray)
Result: [22, 40, 6]
As you saw above the filter method does justice to its name and is used to filter values of an array and returns a new array with those filtered values.
Note: It does not mutate the original array.
Here is what happens: Each element of the original array is passed through a function. The function will return either true or false. The element for which the function returns true will be appended to the new array and the element for which the function returns false will be discarded.