Javascript Array filter()

Introduction

The filter() method returns a new array.

The new array contains all elements that pass the provided test function.

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






Not






Function is a predicate.
It tests each element of the array.
Return true to keep the element, false otherwise.
It accepts three arguments:
element - The current element being processed.
index - Optional, index of the current element.
array - Optional, the whole array.
thisArg
Optional
Value to use as this when executing callback.

If no elements pass the test, an empty array will be returned.

filter() does not change the array on which it is called.

The range of elements processed by filter() is set before the first invocation of callback.

Elements appended to the array after the call to filter() begins will not be visited by callback.

The following example uses filter() to remove elements less than 10.

function isBigEnough(value) {
  return value >= 10
}

let filtered = [12, 5, 8, 130, 44].filter(isBigEnough)
console.log(filtered);/*from   www  . j a  v a2 s .co m*/

The following example returns all prime numbers in the array:

let array = [4, 6, 8, 9, 12, 53, -17];

function isPrime(num) {
    if (num <= 1)
        return false;
    else if (num === 2)
        return true;
    else {/*from   w  w w.  jav a  2s . c  o m*/
        for (let i = 2; i < num; i++)
            if (num % i === 0)
                return false;
        return true;
    }
}

console.log(array.filter(isPrime));  

Calling filter() method when the array is modified.

// Modifying each words
let words = ['A', 'B', 'CSS', 'Javascript']

const modifiedWords = words.filter( (word, index, arr) => {
  arr[index+1] +='long'
  return word.length < 6
})
console.log(modifiedWords)//from  w  ww  .j  av a2  s  .  c o m

To return an array of all numbers greater than 2:

let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1]; 
                      /*from   w ww . j  a va 2s  .  c om*/
let filterResult = numbers.filter((item, index, array) => item > 2);            
console.log(filterResult);   // [3,4,5,4,3] 



PreviousNext

Related