Understand filter in javascript.

Javascript filter method.

filter() is used to filter the array and creates a new array with the elements which satisfy the condition provided as predicate function .

filter method takes a predicate( predicate is commonly understood to be a Boolean-valued function P: X→ {true, false}) as argument , to test each element of the array satisfy condition provided. Each element of the array is passed to that function and checked against the condition provided in that function . If the function returns true then the current element will be added to resulting array.

Example 1 : given an array find odd numbers.

let array = [1,2,3,4,5,6,7,8,9,10];
let oddArray = array.filter( (number) => return number%2 );

NOTE::-- the predicate can be simplified as,
let oddArray = array.filter( number => number%2 );

In the above Example 1 we have an array with numbers from 1 to 10. When we use filter function on that array , it will loop every element and pass each element to the predicate function and check if number%2 , number%2 evaluates to 0 for even numbers and 1 for odd numbers. So for odd numbers it returns 1, so that the odd numbers are added to the resulting array.

EXERCISE SUMS :

  1. [1,2,3,4,5,6,7] find the numbers which are greater than 6.
  2. [“abC”, “bac”, “cad”, ”dad”] find the string which is palindrome.

EXAMPLE 2 :

The predicate function can take three arguments.

element[, index[, array]
  1. element → current element of the array on each looping operation
  2. index → current Index
  3. array → source array

Now , [1,2,3,4,5,6,7,8,9,10] we are going to change all the odd numbers into even numbers in this array , (we can change an odd number to even number by adding +1 to it). Here we are changing in its original array itself. This example is used here because to show how to use all three arguments of the predictive function.

var array = [1,2,3,4,5];
array.filter((element, index, sourceArray) => {

if(element %2 === 1) {

sourceArray[index] += 1;
     }
})
log(array); // [2, 2, 4, 4, 6]

Exercise :

  1. [“one”, “two”, ”three”] reverse all the elements of the array

Follow Jagathish Saravanan for more interesting posts

Leave a comment

Design a site like this with WordPress.com
Get started