How to Filter an Array with Multiple Conditions in JavaScript

To filter an array with multiple conditions in JavaScript, you can use the “Array.prototype.filter()” method. You can combine multiple conditions using logical operators such as “&& (AND)” or “|| (OR)” in the callback function provided by the filter() method.

Example

const items = [
  { id: 1, category: 'Electronics', price: 150 },
  { id: 2, category: 'Electronics', price: 300 },
  { id: 3, category: 'Books', price: 20 },
  { id: 4, category: 'Books', price: 15 },
];

const filteredItems = items.filter(
  (item) => item.category === 'Electronics' && item.price <= 200
);

console.log(filteredItems);

Output

[ { id: 1, category: 'Electronics', price: 150 } ]

In this code, the filter() method finds items with the category property equal to ‘Electronics’ and the price property less than or equal to 200.

You can replace or add conditions in the callback function to filter the array based on your requirements.

Leave a Comment