Using filter() method in Javascript

Using filter() method in Javascript

Introduction

JavaScript array has many iteration methods like, map(), filter(), reduce(). We discussed Reduce method and Map method in the previous articles. Today we will be talking about the Filter() method.

What is filter method?

Filter method iterates through an array and returns the element that passes the test (provided as a function). It returns a new array and, it doesn't mutate the array it is being called on.

The filter() method creates a new array with all elements that pass the test implemented by the provided function. Source MDN.

Prerequisite

  • You must understand how an array works.
  • You must have the basic knowledge about ES6 Arrow function.

The syntax:

let newArray = arr.filter(callback(element[, index, [array]])[, thisArg])

Callback function: A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array, returns true if the element passes the test, otherwise false.

it takes three arguments:

  • element: The current element being processed in the array.

  • index: The index of the element being processed in the array.

  • array: The array filter is called on.

thisArg: The value to use as this when executing callback.

Returned value: An array containing element that passed the test. If no element passes the test an empty array will be returned.

Note: filter() does not execute the function for array elements without values.

Using filter() method

Problem 1: Return an array of all the values in the ages array that are 20 or over in the arr = [23, 54, 89, 72, 17, 12, 62, 15, 18, 74]

Solution

let arr = [23, 54, 89, 72, 17, 12, 62, 15, 18, 74];
let filteredAge = ages.filter(a => a >= 20)
console.log(filteredAge) //[23, 54, 89, 72, 62, 74]

Problem 2: using filter() to filter array content based on search criteria.

Solution

let fruit = ['banana', 'apples', 'mango', 'orange', 'tomato', 'pineapple', 'pawpaw']
//filter array items based on search criteria (keyword)
let filteredItems = (arr, keyword) => {
    //converts to lowercase 
    //checks if keyword is in the current element
    return arr.filter(a => a.toLowerCase().indexOf(keyword.toLowerCase()) !== -1)
}
co
nsole.log(filteredItems(fruit, 'pp')) //returns ["apples", "pineapple"]

Conclusion

Hope this is a useful explanation of the filter() method in JavaScript. Give it a try if you are not using it already.