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
Getting Started with Solid
Getting Started with Svelte
Git Tutorial: Learn how to use Version Control
How to Serve Static Files with Nginx and Docker
How to deploy a .NET app using Docker
How to deploy a MySQL Server using Docker
How to Scrape the Web using Node.js and Puppeteer
Getting Started with Handlebars.js
Building a Real-Time Note-Taking App with Vue and Firebase
Using Axios to Pull Data from a REST API
How To Create a Modal Popup Box with CSS and JavaScript
