How to filter an array in JavaScript using multiple conditions

In this tutorial, let’s look at the different ways to filter an array in JavaScript using multiple conditions.

To start with, let’s look at a what the ‘filter’ method is, and how it can be used to filter an array.

Then, let’s start looking at the different ways of filtering an array by making it confirm to multiple conditions, including:

  1. Using the && logical operator (AND)
  2. Using optional filtering with the ‘||’ operator (OR)
  3. Filtering an array of objects
  4. Combining both AND and OR to filter an array
  5. Using the ‘if’ statement and ‘for’ loop to give multiple conditions
  6. Using the ‘every method to filter the array, and so on.

The ‘filter’ method explained

The ‘filter’ method, as the name implies, can be used to filter the array using any given condition. It’ll create a new array with the extracted values, which can be used as is or reassigned to the original array to modify it.

The filter condition as such does not modify the original array. It just creates a copy of the extracted values.
Look at the code snippet below:

const nums = [11,51,4,30,60];

let result = nums.filter((num) => {
  return num <= 30;
});

console.log(result); //[11, 4, 30] 

As you can see, we have an array with some random numbers ranging from 1 to 60. What if we want to extract only the numbers that are less than 30?

To do that, use the ‘filter’ method on the ‘nums’ array. This method,

  1. Iterates through the entire array.
  2. Stores the current array value in a temporary variable for every iteration. For our example, we’ve named the variable ‘num’. You can name it anything you want.
  3. Will also check the given condition for every iteration. In our example, we’re checking if the current value in ‘num’ is less than or equal to 30. If it is, we’re returning it. Otherwise, it’ll skip the iteration
  4. Will return a new array with all the filtered values at the end of all the iterations. In our code example, we’ve saved this array in a new variable ‘result’, which we then print out.

This is how the ‘filter’ method works in general. As you can see, so far, we’re only checking one condition for every iteration. That doesn’t seem realistic in real-world programming. You might have more than one condition, or you might want to do more complex calculations before you arrive at a result that can be used for filtering.

Either way, you need something more than the basic syntax. In this tutorial, we’ll look at how to expand the conditions used in the ‘filter’ method; especially, how to use multiple conditions for filtering.

Using the ‘&&’ logical operator to filter the array using multiple conditions

One of the simplest ways to add multiple conditions in the ‘filter’ method is by using the ‘&&’ logical operator.

This operator refers to the ‘AND’ condition, where BOTH the conditions that use this operator as a conjunction should be true for the entire statement to be true.

Let me explain this further. Look at the logical statement below:

(a >= 5) && (a <= 10) 

As you can see, we’re dealing with two conditions here,

1. ‘a’ must be greater than or equal to 5, and
2. ‘a’ must be less than or equal to 10.

Let’s say the value of ‘a’ is 7. Apply this value to the above statement, and you’ll get back ‘true’ because 7 is greater than 5 as well as less than 10.

On the other hand, 3, 30 or any of the other numbers not between 5 and 10 will give you a ‘false’.

This is how the ‘AND’ condition works. Both the conditions must be true for the entire statement to be true.

So, if you want multiple conditions to be true while filtering, you can use this operator.

Let’s do that then. Let’s apply two conditions to the code snippet we looked at before. Look below:

const nums = [11,51,4,30,60];

let result = nums.filter((num) => {
  return num >= 10 && num <= 30;
});

console.log(result); //[11, 30] 

As you can see, we’ve added a second condition that says the number should be greater than or equal to 10.
Now, the resultant filtered array will only have 2 numbers (11 and 30) instead of the original 3.

Adding more than 2 conditions

You can of course add more than 2 conditions using the ‘&&’ operator. The result will be the same.

If you have 3 separate conditions joined by 2 ‘&&’ operators, then all 3 must be true for the entire statement to return true. Even if one of the conditions return false, but the remaining 2 are true, the entire statement will return false.

Now, let’s try applying 3 conditions to the same code snippet.

 let result = nums.filter((num) => {
  return num >= 10 && num <= 30 && num != 11;
});

console.log(result); //[30] 

We’ve added a new condition that checks if the number is not equal to 11. So, any number from 10 to 30 (including both 10 and 30), if it’s not equal to 11, will be filtered into the new array.

Consequently, our filtered array only has one result now (30) because this is the only value that matches all 3 of the conditions.

Similarly, you can add as many conditions as you want in your filter condition, as long as they are joined by the ‘AND’ operator.

Optional filtering using the ‘||’ logical operator

The ‘AND’ operator is great if you want ‘ALL’ the conditions specified to be true. What if you want to check multiple conditions, but you don’t care if they’re all true.

If you’re okay with any one of the conditions returning true, then you’re better off using the ‘||’ operator, which is the symbol used for the ‘OR’ operator.

As the name implies, if any one of the conditions using the ‘OR’ operator returns true, the entire statement will return true.

The entire statement will return false only if ALL the conditions return false.

Remember the conditional statement we looked at before? Let’s modify that with the ‘||’ operator.

(a >= 5) || (a <= 10) 

In the above statement, if the number is either greater than or equal to 5 OR lesser than or equal to 10, then you’ll get back a true.

Did you see the issue with this statement. With how things have been set up, every single number, even negative numbers, will pass this test, because every number would either be less than 5 or greater than 10.

But you get the idea. If you are okay with just one of the conditions being true, use the ‘||’ operator.

Now, let’s apply this operator to the array we’ve been working with.

Look at the modified code snippet below:

const nums = [11,51,4,30,60];

let result = nums.filter((num) => {
  return num >= 50 || num == 4;
});

console.log(result); //[51, 4, 60] 

As you can see, we’ve changed the condition so that any value that is,

1. Greater than or equal to 50 OR,
2. Equal to the number 4

Will be filtered out.

So, the result was 51, 60 and 4.

Just like with the ‘AND’ operator, you can apply more than one ‘OR’ operator to the same statement to arrive at a combined result as well.

But true to its nature, no matter how many ‘||’ operators your statement has, even if one of those holds true, the entire statement will be true, even if the remaining conditions are false.

Filtering an array of objects with multiple conditions

You can also apply multiple conditions to filter an array of objects. To do this, let’s create an array ‘people’, whose elements are all objects.

For now, let’s make sure each object has the same properties (name, age, gpa).

const people = [
  {
    name: 'John',
    age: 15,
    gpa: 8
  },
  {
    name: 'Amber',
    age: 16,
    gpa: 9
  },
  {
    name: 'Raj',
    age: 15,
    gpa: 8.5
  },
  {
    name: 'Susan',
    age: 16,
    gpa: 7.8
  }
] 

Now, let’s apply the ‘filter’ method on this array. For every iteration, this method will access one of the objects, which will be stored in the temporary variable ‘person’.

For every iteration, let’s check if person.age is 15 and person.gpa is greater than or equal to 8. If it is, return that object.

When you print the result, you’ll notice the objects with information on John and Raj were filtered from the array because they’re the only 2 students who’re 15 years old AND have a gpa greater than 8.

let result = people.filter((person) => {
  return person.age == 15 && person.gpa >= 8;
});

console.log(result); //[{name: 'John', age: 15, gpa: 8},{name: 'Raj', age: 15, gpa: 8.5}] 

On the other hand, if you use the ‘||’ operator on these two conditions, then you’ll retrieve the objects with information on John, Raj and Amber because now, the student can either be 15 years old OR have a gpa greater than 8.

let result = people.filter((person) => {
  return person.age == 15 || person.gpa >= 8;
});

console.log(result); //[{name: 'John', age: 15, gpa: 8},{name: 'Amber', age: 16, gpa: 9},{name: 'Raj', age: 15, gpa: 8.5}] 

You can play around with these conditions to arrive at different filtered results.

Complex conditions with AND, OR and NOT operators

You can perform complex conditions with a mix of the ‘AND’, ‘OR’ and ‘NOT’ operators as well. Let’s look at an example of the same now.

Let’s use the same array of objects we used in the previous section, but modify the conditions a little like this:

  1. The person’s age is 15 OR,
  2. If the person’s age is 16, they should also be named ‘Susan’ (which would leave out Amber).

If we run these conditions, we should retrieve John, Raj and Susan’s entries. Let’s try.

let result = people.filter((person) => {
  return person.age == 15 || (person.age === 16 && person.name == 
    'Susan');
});

console.log(result); //[{name: 'John', age: 15, gpa: 8},{name: 'Raj', age: 15, gpa: 8.5},{name: 'Susan', age: 16, gpa: 7.8}] 

As you can see above, we have 2 parts to our statement. The && condition is within a parenthesis. Why is that?

That’s because we want the two conditions on either side of the && to be evaluated together and separately from the rest of the statement.

So, the entire statement will be evaluated from left to right. The program will first check if the age is 15. If it is, the entire statement is true be default (because of the || condition in between).

If age is not 15, it’ll go to the next part of the condition, which will check if age is 16 and the person’s name is Susan. If it is, the entire statement will be true again.

If both conditions on either side of ‘||’ were false (age is not 15 and name is not Susan), then the entire statement will return false.

Like this, you can mix and match the conditions to arrive at different results.

Using ‘if’ and ‘else’ statements to give multiple conditions

You can also use the ‘if’ and ‘else’ statements to give multiple conditions to filter an array or an array of objects.

Look at the code snippet below:

let result = people.filter((person) => {
  if(person.age === 15) {
    return true;
  }
  else if(person.age === 16) {
    if(person.name === 'Susan') {
      return true;
    }
  }
  else {
    return false;
  }
});

console.log(result); //[{name: 'John', age: 15, gpa: 8},{name: 'Raj', age: 15, gpa: 8.5},{name: 'Susan', age: 16, gpa: 7.8}] 

As you can see, we’re checking for 3 different conditions (where one of those conditions is nested inside the other) using the ‘if, else if, and else’ statements.

We’re returning true (and in turn, the array element pertaining to the current iteration) if,

  1. The person’s age is 15, or
  2. If the person’s age is 16 AND their name is Susan.

Otherwise, we’re returning false.

Remember how we used this condition in a previous code snippet that had both the ‘AND’ and ‘OR’ operator? We’re just writing the same condition using the ‘if else’ statement.

Using the ‘every’ method to filter the arrays

You can also use the ‘every’ method to filter the array while checking for multiple conditions.

To do this, we’re going to modify the ‘people’ array a little.

We’re going to remove the ‘age’ property in John’s data and add the ‘sports’ property in place of it. For Susan’s data, we’re going to retain the remaining properties while adding the ‘sports’ property.

The properties of the rest of the objects will remain the same.

const people = [
  {
    name: 'John',
    gpa: 8,
    sports: 'Football'
  },
  {
    name: 'Amber',
    age: 16,
    gpa: 9
  },
  {
    name: 'Raj',
    age: 15,
    gpa: 8.5
  },	
  {
    name: 'Susan',
    age: 16,
    gpa: 7.8,
    sports: 'Tennis'
  }
]; 

Now, let’s filter this array by applying the following steps:

  1. Let’s create a new array ‘keys’ with the values ‘age’ and ‘sports’. This refers to some of the properties of the ‘people’ array’s objects.
  2. Next, let’s filter the ‘people’ array. For every iteration, let’s apply the ‘every’ method on the ‘keys’ array. This will iterate separately through the ‘keys’ array inside the current iteration of the ‘people’ array.
  3. While iterating, let’s check if person[key] and person[key], which would be person[age] AND person[sports], are NOT undefined, meaning, if the current object has BOTH the properties.
  4. If they have both the properties, return the object, but do nothing otherwise.
let keys = ['age','sports'];

let result = people.filter((person) => {
  return keys.every(key => person[key] != undefined && person[key] != undefined);
});

console.log(result); //[{name: 'Susan', age: 16, gpa: 7.8, sports: 'Tennis'}]

If you remember, only Susan’s details contain information on both age and sports, so our program only retrieves her data.

That’s it! We’ve looked at a every possible way to filter an array using multiple conditions in JavaScript.

Leave a Comment