JavaScript Array filter() Tutorial

In this section, we will learn what the Array filter() method is and how to use it in JavaScript.

JavaScript Arrays filter() Method

The `filter()` method is used to create a new array from another array by applying a filter on the elements of the old array.

This filter is basically a function that will be executed for each element in the old array and if the result of this function is `true` the target element will be added to the new array.

Array filter() Syntax:

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

Array filter() Method Parameters:

The `filter()` method takes two arguments.

The first argument is a reference to a function. For each element in the target array, the filter method will call the reference function.

This function takes 3 arguments:

  • The first argument is the element in the array.
  • The second argument is the index of that element.
  • The third argument is a reference to the target array.

Inside this function, we specify a set of instructions that will run for each element and at the end, will return either `true` or `false`. As mentioned before, any element that caused the result true in this function will be added to the new array. So those elements that result false are ignored.

Other than the function, the `filter()` method takes a second argument as well. This second argument, which is optional, is a reference to an object that will bind to the `this` keyword in the target function that we passed as the first argument.

Array filter() Method Return Value:

The result of the `filter()` method is a new array containing all the elements of the old array that passed the test. If no element in the old array passed the test in the function, the returned array will be empty.

Example: JavaScript array filtering

const arr = [23,4,3,23,4,2,32,5,3,23,423,234,2,3,2423,42];
function eve(value, index, arr){
  return value >=100?true: false; 
}

const final = arr.filter(eve);
console.log(final);

Output:

[423, 234, 2423]

Example: JavaScript filter array of objects

const obj1 = {
   name: "John", 
   age: 1000
}
const obj2 = {
   name: "Omid",
   age: 29
}
const obj3 = {
   name : "Jack", 
   age :52
}
const arr = [obj1,obj2,obj3];
function eve(value, index, arr){
  return value.age >=50?true: false; 
}

const final = arr.filter(eve);
for (const obj of final){
   console.log(obj.name);
}

Output:

John

Jack

In this example, we have 3 objects in an array and used the filter() method to get only those objects that have the “age” property with the value greater than 50.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies