DEV Community

Cover image for A Complete Introduction to JavaScript Array filter Method
Yogesh Chavan
Yogesh Chavan

Posted on • Edited on • Originally published at blog.yogeshchavan.dev

A Complete Introduction to JavaScript Array filter Method

The Array filter method is one of the most widely used methods in JavaScript.

It allows us to quickly filter out elements from the array with certain criteria.

So in this article, you will learn everything about the filter method and its various use cases.

So let's get started.


Take a look at the below code that does not use the filter method:

const employees = [
  { name: 'David Carlson', age: 30 },
  { name: 'John Cena', age: 34 },
  { name: 'Mike Sheridan', age: 25 },
  { name: 'John Carte', age: 50 }
];

const filtered = [];

for(let i = 0; i < employees.length; i++) {
 if(employees[i].name.indexOf('John') > -1) {
   filtered.push(employees[i]);
 }
}

console.log(filtered); // [ { name: "John Cena", age: 34 }, { name: "John Carte", age: 50 }]
Enter fullscreen mode Exit fullscreen mode

In the above code, we're finding out all the employees with the name John for that we're using indexOf method.

The for loop code looks complex as we need to manually loop over the employees array and push the matching employee to the filtered array.

But using the array filter method, we can simplify the above code.

Array filter Method

The array filter method has the following syntax:

Array.filter(callback(element[, index[, array]])[, thisArg])
Enter fullscreen mode Exit fullscreen mode

The filter method does not change the original array but it returns a new array with all the elements that satisfy the provided test condition.

The filter method takes a callback function as the first argument and executes the callback function for every element of the array.

Each array element value is passed as the first parameter to the callback function in every iteration of the callback function.

Take a look at the below code using filter method:

const employees = [
  { name: 'David Carlson', age: 30 },
  { name: 'John Cena', age: 34 },
  { name: 'Mike Sheridan', age: 25 },
  { name: 'John Carte', age: 50 }
];

const filtered = employees.filter(function (employee) {
  return employee.name.indexOf('John') > -1;
});

console.log(filtered); // [ { name: "John Cena", age: 34 }, { name: "John Carte", age: 50 }]
Enter fullscreen mode Exit fullscreen mode

Here, using the array filter method, we removed the need of manually looping over the employees array and we don't need to create a filtered array beforehand to filter out the matching employees.

Understanding filter Method

The filter method accepts a callback function for which each element of the array is automatically passed as the first parameter in every iteration of the loop.

Suppose, we have the following array of numbers:

const numbers = [10, 40, 30, 25, 50, 70];
Enter fullscreen mode Exit fullscreen mode

and we want to find out all the elements that are greater than 30, then we can use the filter method as shown below:

const numbers = [10, 40, 30, 25, 50, 70];

const filtered = numbers.filter(function(number) {
  return number > 30;
});

console.log(filtered); // [40, 50, 70]
Enter fullscreen mode Exit fullscreen mode

So Inside the callback function, in the first iteration of the loop, value 10 which is the first element from the array will be passed as a number parameter value and 10 > 30 is false so the number 10 will not be considered as a match.

The array filter method returns an array so as 10 is not greater than 30, it will not be added to the filtered array list.

Then in the next iteration of the loop, the next element from the array which is 40 will be passed to the callback function as a number parameter value and as 40 > 30 is true, it will be considered as a match and will be added to the filtered array.

This will go on till all the elements from the array are not finished looping.

So anytime the callback function returns a false value, that element will not be added to the filtered array. The filter method returns an array containing only those elements for which the callback function returns a true value.

You can see the current value of the element that is passed to the callback function in each iteration of the loop If you log the value to the console:

const numbers = [10, 40, 30, 25, 50, 70];

const filtered = numbers.filter(function(number) {
  console.log(number, number > 30);
  return number > 30;
});

console.log(filtered); // [40, 50, 70]

/* output

10 false
40 true
30 false
25 false
50 true
70 true

[40, 50, 70]

*/
Enter fullscreen mode Exit fullscreen mode

Now, take a look at the below code:

const checkedState = [true, false, false, true, true];

const onlyTrueValues = checkedState.filter(function(value) {
  return value === true;
});

console.log(onlyTrueValues); // [true, true, true]
Enter fullscreen mode Exit fullscreen mode

In the above code, we're finding out only those values which are having a value of true.

The callback function can be written as shown above or using an arrow function as shown below:

const onlyTrueValues = checkedState.filter(value => {
  return value === true;
});
Enter fullscreen mode Exit fullscreen mode

And If there is a single statement in the arrow function, we can skip the return keyword and implicitly
return the value as shown below:

const onlyTrueValues = checkedState.filter(value => value === true);
Enter fullscreen mode Exit fullscreen mode

The above code can be further simplified as:

const onlyTrueValues = checkedState.filter(Boolean);
Enter fullscreen mode Exit fullscreen mode

To understand how it works, check out my this article.

Callback Function Parameters

Apart from the actual element of the array, the callback function passed to the filter method also receives the following parameters:

  • The index of the current element in the array we're looping over
  • The original array which we're looping over

Take a look at the below code:

const checkedState = [true, false, false, true, true];

checkedState.filter(function(value, index, array) {
  console.log(value, index, array);
  return value === true;
});

/* output

true   0  [true, false, false, true, true]
false  1  [true, false, false, true, true]
false  2  [true, false, false, true, true]
true   3  [true, false, false, true, true]
true   4  [true, false, false, true, true]

*/
Enter fullscreen mode Exit fullscreen mode

Use Cases For filter Method

As you have seen above, the array filter method is useful for filtering out data from the array.

But the filter method is also useful in some real use cases like removing duplicates from the array, separate out common elements between two arrays etc.

Remove Element From Array

The most common use case of the filter method is to remove a particular element from the array.

const users = [
  {name: 'David', age: 35},
  {name: 'Mike', age: 30},
  {name: 'John', age: 28},
  {name: 'Tim', age: 48}
];

const userToRemove = 'John';

const updatedUsers = users.filter(user => user.name !== userToRemove);

console.log(updatedUsers);

/* output

[
  {name: 'David', age: 35},
  {name: 'Mike', age: 30},
  {name: 'Tim', age: 48}
]

*/
Enter fullscreen mode Exit fullscreen mode

Here, we're removing the user from the users array whose name is John.

So in the callback function, we're checking for the condition to retain the users whose name does not match with the name stored in the userToRemove variable.

Find Unique Or Duplicates From Array

const numbers = [10, 20, 10, 30, 10, 30, 50, 70];

const unique = numbers.filter((value, index, array) => {
  return array.indexOf(value) === index;
})

console.log(unique); // [10, 20, 30, 50, 70]

const duplicates = numbers.filter((value, index, array) => {
  return array.indexOf(value) !== index;
})

console.log(duplicates); // [10, 10, 30]
Enter fullscreen mode Exit fullscreen mode

The indexOf method returns the index of the first matching element so, in the above code, we're checking if the current index of the element which we're looping over matches with the index of the first matching element to find out unique and duplicate elements.

Find Distinct Values Between Two Arrays

const products1 = ["books","shoes","t-shirt","mobile","jackets"];

const products2 = ["t-shirt", "mobile"];

const filteredProducts = products1.filter(product => products2.indexOf(product) === -1);

console.log(filteredProducts); // ["books", "shoes", "jackets"]
Enter fullscreen mode Exit fullscreen mode

Here, we're looping over the products1 using the filter method and in the callback function, we're checking if the products2 array contains the current element that we're looping over it using the array indexOf method.

If there is no match for that element then the condition will be true and that element will be added to the filteredProducts array.

You can also use array includes method to achieve the same functionality:

const products1 = ["books","shoes","t-shirt","mobile","jackets"];

const products2 = ["t-shirt", "mobile"];

const filteredProducts = products1.filter(product => !products2.includes(product));

console.log(filteredProducts); // ["books", "shoes", "jackets"]
Enter fullscreen mode Exit fullscreen mode

Browser Support For filter Method

  • All modern browsers and Internet Explorer (IE) version 9 and above
  • Microsoft Edge version 12 and above

Thanks for reading!

Check out my recently published Mastering Redux course.

In this course, you will build 3 apps along with food ordering app and you'll learn:

  • Basic and advanced Redux
  • How to manage the complex state of array and objects
  • How to use multiple reducers to manage complex redux state
  • How to debug Redux application
  • How to use Redux in React using react-redux library to make your app reactive.
  • How to use redux-thunk library to handle async API calls and much more

and then finally we'll build a complete food ordering app from scratch with stripe integration for accepting payments and deploy it to the production.

Want to stay up to date with regular content regarding JavaScript, React, Node.js? Follow me on LinkedIn.

Top comments (1)

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan

Thanks for adding that