Categories
JavaScript Answers

How to filter array by multiple conditions with JavaScript?

Spread the love

Sometimes, we want to filter array by multiple conditions with JavaScript.

In this article, we’ll look at how to filter array by multiple conditions with JavaScript.

How to filter array by multiple conditions with JavaScript?

To filter array by multiple conditions with JavaScript, we can use the array filter method.

For instance, we write

const filter = {
  address: "England",
  name: "Mark",
};
const users = [
  {
    name: "John",
    email: "johnson@mail.com",
    age: 25,
    address: "USA",
  },
  {
    name: "Tom",
    email: "tom@mail.com",
    age: 35,
    address: "England",
  },
  {
    name: "Mark",
    email: "mark@mail.com",
    age: 28,
    address: "England",
  },
];

const filteredUsers = users.filter((item) => {
  for (const key of Object.keys(filter)) {
    if (item[key] === undefined || item[key] !== filter[key]) {
      return false;
    }
  }
  return true;
});

console.log(users);

to call users.filter with a callback.

In the callback, we loop through the filter object’s keys we get from Object.keys.

In the loop, we check the value of each filter value to see if they’re what we’re looking for.

If they’re not, we return false.

Otherwise, we return true to include it in the filtered array returned.

Conclusion

To filter array by multiple conditions with JavaScript, we can use the array filter method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *