Just Learn Code

Mastering Array Filtering with Multiple Conditions in JavaScript

Filtering an Array with Multiple Conditions in JavaScript

Programming is all about sorting and filtering data to fit our needs. This is where the Array.filter() method in JavaScript comes in handy.

It enables us to filter an array effortlessly and produce a new array with only those elements that meet certain criteria. In this article, we’re going to explore four different methods of filtering an array with multiple conditions.

We’ll start by looking at how to use the Array.filter() method with logical AND, followed by logical OR. We’ll then learn how to explicitly return true or false with Array.filter() before delving into using a dynamic filter.

Using Array.filter() Method with Logical AND

The logical AND operator allows us to filter an array based on two or more conditions that must be met before an element is included in the new array. We can implement this with the Array.filter() method as follows:

“`javascript

const numbers = [10, 20, 30, 40, 50, 60];

const filteredNumbers = numbers.filter((number) => number % 10 === 0 && number >= 40);

console.log(filteredNumbers); // Output: [40, 50, 60]

“`

In the example above, we filtered the array by checking if each element is divisible by 10 and greater than or equal to 40.

This returned a new array with only the elements that satisfy both conditions. Using Array.filter() Method with Logical OR

The logical OR operator, on the other hand, allows us to filter an array based on two or more conditions where only one condition needs to be met for an element to be included in the new array.

To achieve this, we can use the Array.filter() method as shown below:

“`javascript

const fruits = [‘apple’, ‘banana’, ‘cherries’, ‘dates’, ‘elderberry’];

const filteredFruits = fruits.filter((fruit) => fruit.startsWith(‘a’) || fruit.endsWith(‘y’));

console.log(filteredFruits); // Output: [“apple”, “cherries”, “elderberry”]

“`

In this example, the array is filtered using two conditions. The first condition checks if each element starts with `a`, while the second condition checks if each element ends with `y`.

Once any of these conditions is met, the element is included in the new array. Explicitly Returning True or False with Array.filter()

At times, we may need to perform complex data filtering that requires us to explicitly return true or false.

This can be accomplished by passing a function to the Array.filter() method that returns a boolean value. Let’s take a look at an example:

“`javascript

const people = [

{ name: ‘John’, age: 25, country: ‘USA’ },

{ name: ‘Jane’, age: 18, country: ‘Canada’ },

{ name: ‘Doe’, age: 22, country: ‘USA’ },

{ name: ‘Mary’, age: 40, country: ‘Canada’ },

{ name: ‘Tom’, age: 30, country: ‘USA’ },

{ name: ‘Rachel’, age: 24, country: ‘Canada’ },

];

const filteredPeople = people.filter((person) => {

return person.age >= 25 && person.country === ‘USA’;

});

console.log(filteredPeople);

/* Output:

[

{ name: ‘John’, age: 25, country: ‘USA’ },

{ name: ‘Tom’, age: 30, country: ‘USA’ }

]

*/

“`

In this example, we explicitly return true or false based on whether a person’s age is greater than or equal to 25 and if they’re from the USA.

This results in a new array containing only the persons that satisfy both conditions. Using a Dynamic Filter with Array.filter()

Finally, we can use a dynamic filter to filter an array based on user input or any other variable that changes dynamically.

Here’s an example:

“`javascript

const animals = [‘cat’, ‘dog’, ‘lion’, ‘tiger’, ‘elephant’];

const dynamicFilter = (filter) => {

return animals.filter((animal) => animal.includes(filter));

};

console.log(dynamicFilter(‘t’)); // Output: [“cat”, “tiger”]

console.log(dynamicFilter(‘i’)); // Output: [“lion”, “tiger”, “elephant”]

“`

In this example, we use a higher-order function to create a dynamic filter that takes a filter value as input. This filter value is then used to filter the array based on whether the animal name includes the filter character.

Additional Resources

If you want to learn more about filtering arrays in JavaScript, there are plenty of resources available online. Here are a few suggestions:

– MDN Web Docs: Array.prototype.filter()

– w3schools.com: JavaScript Array filter() Method

– SitePoint: Filtering Arrays with Array.filter()

In conclusion, the Array.filter() method is an incredibly useful tool for filtering arrays with multiple conditions.

With logical operators, explicit return values, and dynamic filters, there are endless possibilities for sorting and filtering data in JavaScript. Use these methods to your advantage and expand your data manipulation capabilities.

In this article, we explored four different methods of filtering an array with multiple conditions in JavaScript. We learned how to use the Array.filter() method with logical AND, logical OR, and how to explicitly return true or false.

We also saw how to use a dynamic filter with the Array.filter() method. Filtering an array is essential in programming, and the Array.filter() method is a powerful tool for doing so.

With the different techniques discussed, we can filter and sort data with ease. The key takeaway is to be familiar with these methods when filtering arrays in JavaScript to optimize code performance and enhance data manipulation capabilities.

Popular Posts