array.filter() method in javascript (react)

To filter array by a condition, javascript provides an inbuild method called filter().

This method takes three arguments-

first, each value of array (one-by-one),

second, respective index of that value in array,

and the last one is the array filter() was called upon.

But usually we pass first two arguments.

How to use the JavaScript filter array method?

Try it :

Passing one argument :

const numbers = [1, 2, 3, 4, 5];

const result = numbers.filter( (number) => word > 2 );
// passing 1 argument

console.log(result);
// Expected output: Array [3, 4, 5]

// filter always returns an array

let’s say we have an Array(numbers), and we want to filter the values greater
then 2 , so we just have to apply the .filter() on Array(numbers).
on parameter we will get every value one by one,

and then every value
would be checked that it is bigger than 2 or not ,
if it is so it would be returned and if it is not so it wouldn’t.

Try it :

Passing two arguments :

const numbers = [6, 7, 8, 9, 10];

  const result = numbers.filter((number, index) => index === 0);
   // passing two arguments
  
  console.log(result);

  // Expected output: Array [6]

In this example we have passed two arguments , first one is each value of array(numbers) and the other one is respective index of that value in array(numbers).

Here we have given the condition(index === 0) that return the array of numbers who’s index is 0, so it will return an array of 1 length.

Try it :

Passing three arguments :

const numbers = [11, 12, 13, 14, 15];

const result = numbers.filter((number,index,array) => array)
   // passing three arguments
  
  console.log(result);

  // Expected output: Array [11, 12, 13, 14, 15]

Here we have passed all three arguments which filter method are allowed to take,
first and the second one we have already discussed,

the last one(array) is, the array(numbers) filter() was called upon.

In above example we have given the condition that return array(numbers) filter( ) was called upon ,

so it will show the array(numbers) in console.

Leave a Comment