How To Filter An Array With Multiple Conditions In JavaScript

Filter an Array with Multiple Conditions in JavaScript

There are situations when we want to filter an array with multiple conditions in JavaScript. In this tutorial, we will demonstrate the idea to solve the problem.

JavaScript Methods to filter an Array with multiple conditions

Method 1: Use Array.prototype.filter()

The filter() method makes a shallow copy of a section of an array that has been narrowed down to only the items of the array that pass the test given by the supplied function, preferably equals ‘true’.

Syntax:

array.filter(function(currentValue, index, yourArr), thisValue)

Parameters:

  • function(): Requisite, a function to run for each array element.
  • currentValue: Requisite, the value of the current element.
  • index: Optional, the index of the current element.
  • yourArr: Optional, the array of the current element.
  • thisValue: Optional – default undefined, a value passed to the function as its ‘this’ value.

Return value: An array that passed the testing field provided by the function.

To start, we will have our data as an array including ‘Product’.

We also construct an array that includes our filter properties.

const Product = [
    {   id: 1,
        name: 'Clothes Hanger',
        manufacturer: 'OEM',
        country: 'CN',
        stock: 400
    },
    {
        id: 2,
        name: 'Plastic Basket',
        manufacturer: 'OEM',
        country: 'N/A',
        stock: 700
    },
    {
        id: 3,
        name: 'Plastic Bucket',
        manufacturer: 'DuTa',
        country: 'TH',
        stock: 100
    }
];

The most simple scenario where you filter a specific property’s value based on your project, you can directly use dot annotations to pass the logical expression into the array.prototype.filter() method as follows:

results = Product.filter(obj =>{
    if (obj.manufacturer != 'OEM' || obj.country != 'CN')
        return false;

    return true;
})

console.log(results);

Output:

[
  {
    id: 1,
    name: 'Clothes Hanger',
    manufacturer: 'OEM',
    country: 'CN',
    stock: 400
  }
]

However, if your conditions are unspecified. Presumably, your users will select the value of your conditions, which would be stored in an array.

const filters =
    {
        manufacturer: 'OEM',
        country: 'CN'       
    };

Method 2: Combine with function and the conditions

To get an array that match our filter field, we will construct a function as such:

arrayFilter = function (targetArray, filterArray){
    return targetArray.filter(function(item) {
       for (var key in filterArray) {
          if (item[key] === undefined || item[key] != filterArray[key])
            return false;
       }

       return true;
  });
}

results = arrayFilter(Product,filters);
console.log(results);

Output:

[
  {
    id: 1,
    name: 'Clothes Hanger',
    manufacturer: 'OEM',
    country: 'CN',
    stock: 400
  }
]

Code explanation:

We write a function that uses a filter array to filter our target array and returns an array that passes the testing field.
Every key in our filter array is checked to see whether it exists in our target array or if its values match those in the filter array.
The method returns “false” if any conditions are not met, and filter() will skip that key.
The item is included in the array to be returned if the method returns “true.”

Summary

We have covered two situations where you need to filter an array with multiple conditions in JavaScript. You may be interested in how arrays and objects are handled in JavaScript and how to interact with them. If you have any problems, please comment below. We will respond as possible, thank you for reading!

Maybe you are interested:

Leave a Reply

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