Home Web DevelopmentJavaScript Filtering in JavaScript

Filtering in JavaScript

The filter() method returns a new array containing elements that pass a function’s test. The filter() method does not run the function for empty elements. The original array is unaffected by the filter() technique.

Example 1: Filter ages above 30

Return an array of all values in ages[] that are 30 or over:

function checkAgeAbove30(age) {
  return age >= 30;
  }

const ages = [37, 38, 21, 45, 12, 19];

const result = ages.filter(checkAgeAbove30);
console.log(result)
check ages above 30
check ages above 30

Syntax

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


// Arrow function
filter((element) => { /* ... */ } )
filter((element, index) => { /* ... */ } )
filter((element, index, array) => { /* ... */ } )

// Callback function
filter(functionCallback)
filter(functionCallback, thisArg)

// Inline callback function
filter(function(element) { /* ... */ })
filter(function(element, index) { /* ... */ })
filter(function(element, index, array){ /* ... */ })
filter(function(element, index, array) { /* ... */ }, thisArg)

Parameters

ParameterDescription
function()Required. The function() runs for every element in the array.
currentValueRequired. It refers to the current elements’ value.
indexOptional. It is the current elements’ index.
arrOptional. It refers to the current elements’ array.
thisValueOptional. By default, it is undefined. It refers to the value that is passed to the function()


Return Value

TypeDescription
An arrayHave the elements passed the provided test?
It returns an empty array on the off chance that none of the elements passes the given test.


Description

filter() invokes a supplied callback function once for each element in an array and then creates a new array containing all the values for which the callback function returns a true value. The callback function is only called for array indexes that have been assigned values; it isn’t called for indexes that have been removed or have never had values assigned to them. Array elements that fail the callback function test are not included in the new array and skipped.

The callback function is called with three arguments:

  • The element’s value – This is the element in the array currently being iterated over.
  • The element’s index – This is the index position of the currentItem inside the array.
  • The Array object being traversed represents the target array and all its items.

If the callback is given a thisArg parameter, it will be utilized as the callback’s value. Otherwise, undefined will be used as the value for this. This value that the callback function eventually sees is determined using the standard procedures for determining the ‘this’ viewed by a function.

The array on which filter() is invoked is not mutated.

Before the initial invocation of function callback, the range of elements handled by filter() is configured. Function callback will not visit elements assigned to indexes that have already been visited or those outside the range. Existing array items are not be visited if they are deleted in the same way.

The type of concurrent alteration described in the preceding paragraph typically results in difficult-to-understand code and should be avoided (except in exceptional cases).

Example:

const selected_words = ['home', 'limit', 'explore', 'exuberant', 'adventurous', 'rest'];

const expected_result = selected_words.filter(word => word.length > 6);

console.log(expected_result);

Array Searching

The example below uses the filter() to filter array data depending on the search criteria provided.

let computers = ['HP', 'Dell', 'Lenovo', 'IBM', 'Chromebook']

/**
 * Filter array items based on search criteria (query)
 */
function filterItems(arr, query) {
  return arr.filter(function(el) {
    return el.toLowerCase().indexOf(query.toLowerCase()) !== -1
  })
}

console.log(filterItems(computers, 'D'))  //
console.log(filterItems(computers, 'Ch'))  //
searching an array
searching an array

Example: How to Filter Invalid JSON entries

This example demonstrates how to use filter() to create a filtered JSON file of all the elements with a numeric id that is not zero.

let arrVals = [
 { id: NaN },
  { id: 97 },
  { id: -12 },
  { id: 0 },
  { id: null },
  { id: 7 },
  { id: 20.52 },
  { },
  { id: 'undefined' }
]

let wrongEntries = 0

function filterArrayValuesByID(item) {
  if (Number.isFinite(item.id) && item.id !== 0) {
    return true
  }
  wrongEntries++
  return false;
}

let resultArray = arrVals.filter(filterArrayValuesByID)

console.log('Resultant Filtered Array: \n', resultArray)
how to filter Invalid JSON entries
how to filter Invalid JSON entries

Example: Find all prime numbers in an array

The following example returns all prime numbers in the array.

const arrayVals = [-8, -7, -6, 0, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];

function checkIfNumberPrime(val) {
  for (let j = 2; val > j; j++) {
    if ( val % j == 0) {
      return false;
    }
  }
  return val > 1;
}

console.log(arrayVals.filter(checkIfNumberPrime));
find all prime numbers in array
find all prime numbers in array

Example: Filtering out values smaller than 50

In the example below, the filter() function filters out values smaller than 50 and returns those above 50.

function valuesAboveFifty(val) {
  return val >= 50
}

let filtered_vals = [32, 25, 28, 150, 64].filter(valuesAboveFifty)
console.log(filtered_vals)
filter values smaller than 50
filter values smaller than 50

Example: How to add new words to an existing array

This example illustrates how to add new words to those already existing in an array using the filter() function.

// Adding new words to the exsiting
laptops = ['HP', 'Dell', 'Chromebook', 'Apple', 'IBM']
const appendedWords = laptops.filter( (laptops, index, arr) => {
  arr.push('Google')
  return laptops.length < 4
})
Add new words to an array
Add new words to an array

Example: Modifying every word in an array

This example shows how each item in the array is modified by using the filter() function.

// Modifying individual words in an array
laptops = ['HP', 'Dell', 'Chromebook', 'Apple', 'IBM']

const updatedWords = laptops.filter( (word, index, arr) => {
  arr[index+1] +=' extra'
  return word.length < 6
})

console.log(updatedWords)
Modifying every word in an array
Modifying every word in an array

Example: How to Delete words using filter

In this example, the filter() function deletes words meeting specified criteria in an array.

laptops = ['HP', 'Dell', 'Chromebook', 'Apple', 'IBM']
const deleteWords = laptops.filter( (laptop, index, arr) => {
  arr.pop()
  return laptop.length < 5
})

console.log(deleteWords)
How to Delete words using filter
How to Delete words using filter

Conclusion

The filter() Array method takes an existing array and creates a new array with elements that meet a set of criteria. The filter() method operates in a very straightforward manner. It comprises selecting one or more things (a subset) from a larger group of objects (a superset) based on a criterion or preference.

We all do it daily, whether we’re reading, picking friends or spouses, or deciding what movie to watch. The filter() method also accepts a callback function and uses it to call it for each item iterating over in the target array.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More