JavaScript code recipe: filtering array with multiple values

When you need to filter an array with multiple values or criteria, you can use the .filter() and write multiple validations in the callback function.

If you need a reminder on the filter method, here's a quick introduction. Otherwise, Let's see an example of multiple filters in action.

Let’s say you have an array of numbers as follows:

let numbers = [3, 7, 2, 15, 4, 9, 21, 14];

You want to filter the numbers to include only those higher than 3 and lower than 17.

Here’s how you do it with .filter():

let numbers = [3, 7, 2, 15, 4, 9, 21, 14];let filteredNumbers = numbers.filter(function (currentElement) {
return currentElement > 3 && currentElement < 17;
});
console.log(filteredNumbers);

The value of filteredNumbers will be [7, 15, 4, 9, 14]

As long as you return either true or false, you can create as many validation logic as you need inside the callback function of filter. You can also write the previous filter as follows:

let numbers = [3, 7, 2, 15, 4, 9, 21, 14];let filteredNumbers = numbers.filter(function (currentElement) {
if (currentElement > 3 && currentElement < 17) {
return true;
}
});
console.log(filteredNumbers);

When the filter callback function doesn’t return true, the currentElement won’t be pushed into the resulting array.

Filter array of objects with multiple values

You can filter an array of objects by testing whether the properties match a certain set of criteria.

Let’s see another example. Let’s say you have a list of people data as follows:

let people = [
{
name: "Steve",
age: 27,
country: "America",
},
{
name: "Linda",
age: 23,
country: "Germany",
},
{
name: "Jimena",
age: 29,
country: "Spain",
},
{
name: "Eric",
age: 24,
country: "England",
},
{
name: "Jacob",
age: 24,
country: "America",
},
];

Now you need to filter the data to only include those from America and age below 25. Here’s how you do it:

let filteredPeople = people.filter(function (currentElement) {
// the current value is an object
// so you can check on its properties
return currentElement.country === "America"
&& currentElement.age < 25;
});
console.log(filteredPeople);

Only the last element will match the filter:

{name: "Jacob", age: 24, country: "America"}

More JavaScript goodies:

A senior software developer with experience in full-stack JavaScript. Nathan has published over 100 JavaScript tutorials at https://sebhastian.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store