How to filter an array with multiple conditions in JavaScript

To filter an array with multiple conditions in JavaScript, use the array.filter() method. The array.filter() is a built-in JavaScript function that checks the elements of each array from the function given in the array method and returns their array. If any element in the array is against the statement of function, then the element of that array is removed. The filter() function makes no changes to the original array.

Syntax

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

Arguments

function():

This is a necessary argument of the function. This defines that the function will run for each of the elements present in the array.

currValue:

This is again a necessary argument of the function. This defines the value of the current element in the array.

index:

This is an optional argument of the function. This defines the index of the current element in the array.

arr:

This is again an optional argument.

thisValue:

This is an optional argument. By default, it assumes the value undefined.

Return value

It returns an array containing the elements according to the sets of conditions satisfied by the given function. However, if no element meets the conditions, it will simply return an empty array.

Example

Let’s say we have an array of candidate ages.

let candidateAges = [10, 15,19, 21, 12, 14, 25, 40];

And we want to filter the candidates ages greater than 18 years and less than 25 years. Therefore, we must pass a validation function inside the filter() function.

function (currentAge) {
  return currentAge > 18 && currentElement < 25;
}

Let’s see the complete code.

let candidateAges = [10, 15, 19, 21, 12, 14, 25, 40];

let currentAge = candidateAges.filter(function (currentAge) {
    return currentAge > 18 && currentAge < 25;
});

console.log(currentAge);

Output

[ 19, 21 ]

In this example, we declared an array “candidateAges,” consisting of some age values. Our target is to filter the array with ages greater than 18 and less than 25. So we are using the filter() function here, which is taking a callback function inside which we are applying two validations currentAge > 18 and currentAge < 25.

After that, we assign the output array to ‘currentAge’ and print it using the console.log() function.

That’s it for this tutorial.

See also

How to Prevent Duplicates in Array in JavaScript

How to Add Property to Array of Objects in JavaScript

How to flatten Array of Objects in JavaScript

Leave a Comment