How to Filter Array with Multiple Conditions in JavaScript
Table of Contents
JavaScript comes with a built-in filter
method on the Array class that helps you filter an array.
In this post, we'll learn how to you can use this method to filter an array using multiple conditions at the same time.
Using the filter method
Before we use it with multiple conditions, let's first use it with a single condition.
Let's start with a basic array of objects:
JAVASCRIPTconst array = [
{ name: "John", age: 30 },
{ name: "Jane", age: 25 },
{ name: "Joe", age: 35 },
];
Let's say we only wanted to get the names of the people who are 30 or older.
Let's use the filter
method for this. This method takes a callback function that will be called for each element in the array, and if the callback returns true
, the element will be included in the new array.
Here's an example using one condition:
JAVASCRIPTconst filtered = array.filter(element => element.age >= 30);
console.log(filtered);
BASH(2) [{…}, {…}]
0: {name: 'John', age: 30}
1: {name: 'Joe', age: 35}
As expected, because both John
and Joe
passed the condition, they were included in the new array.
Now let's move on to using multiple conditions.
Using multiple conditions
The filter
method can be used with multiple conditions by using the &&
operator.
This operator essentially combines two conditions into one, allowing you to filter an array using multiple conditions.
Let's say we wanted to get the names of the people who are older than 20 but younger than 30.
JAVASCRIPTconst filtered = array.filter(element => element.age > 20 && element.age < 30);
console.log(filtered);
BASH0: {name: 'Jane', age: 25}
length: 1
Just like before, because Jane
was the only person with an age that passed both conditions, she was included in the new array, and nobody else.
Conclusion
In this post, we learned how you can use the filter
method with multiple conditions by using the &&
operator to combine two separate conditions.
This allows you to filter an array as specifically as you want, giving you a lot of flexibility.
Hopefully, this helps you and thanks for reading!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Getting Started with Express
- Create an RSS Reader in Node
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to deploy a PHP app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- Getting Started with Sass
- Getting Started with Handlebars.js
- Getting Started with React