Javascript filter array element with multiple conditions

Javascript filter array multiple conditions Example; In this tutorial you how how to filter JavaScript array with multiple conditions. Below we have added best examples to filter JavaScript array elements with multiple conditions, you just need to call the Array object’s filter() method.

You can use Array.filter with logical AND && or OR || operator to usiing the multiple condition. Array.filter returns all elements that satisfy the conditions.

Syntax: Here is the syntax of filter with mulitple conditions with AND (&&) operation and OR (||) operator;

// REQUIRED multiple conditions
const data = arr.filter(function (element) {
  return // condition1 && condition2 && condition3...
});

//OPTIONAL multiple conditions
const data = arr.filter(function (element) {
  return // condition1 || condition2 || condition3...
});

JavaScript filter array with multiple AND (&&) conditions

const users = [
  {name: 'John', age: 20},
  {name: 'Bjorn', age: 30},
  {name: 'Leon', age: 20},
];

const results = users.filter(user => {
  // using AND (&&) operator
  return user.age === 30 && user.name === 'Bjorn';
});

console.log(results); //  [{name: 'Bjorn', age: 30}]

The filter method returns a new array filled with elements that pass the test defined in the callback function.

JavaScript filter array with multiple OR (||) conditions

If you need to filter an array with multiple conditions where only one condition has to be satisfied, use the Array.filter method with the || (or) operator.

const users = [
  {name: 'John', age: 20},
  {name: 'Bjorn', age: 30},
  {name: 'Leon', age: 20},
];

const results = users.filter(user => {
  // using AND (&&) operator
  return user.age === 30 && user.name === 'John';
});

console.log(results); //  [{name: 'John', age: 20}, {name: 'Bjorn', age: 30}]

I hope you like these examples.