How to Filter Array Multiple Values in JavaScript

Mehvish Ashiq Feb 02, 2024
  1. Use the filter() Method to Filter an Array by Checking Multiple Values in JavaScript
  2. Use the filter() Method to Filter an Array of Objects by Checking Multiple Values in JavaScript
  3. Use the filter() Method to Filter an Array of Objects Dynamically in JavaScript
How to Filter Array Multiple Values in JavaScript

The filter() method creates a brand new array with those elements that have passed a test function.

Use the filter() Method to Filter an Array by Checking Multiple Values in JavaScript

For instance, we will retrieve the student’s records whose last name starts with M and enroll in at least 3 courses.

The filter() function does not modify/update the original array and runs for empty elements.

var array = [1, 3, 4, 2, 6, 7, 5, 9, 10, 8];
var result = array.filter(array => array < 10 && array >= 2);
console.log(result);

Output:

[3, 4, 2, 6, 7, 5, 9, 8]

Here, we are using the arrow function inside the filter() method.

Remember, we can also pass the function name and write that function separately. This array function gets executed for each element in the array and examines if the specified criteria are satisfied or not.

Then the element would be saved in the result array otherwise, move to the next element of the array.

Use the filter() Method to Filter an Array of Objects by Checking Multiple Values in JavaScript

Here, we have a cities array with 4 objects.

Each object has two properties, city_name and city_population.

let cities = [
  {city_name: 'Los Angeles', city_population: 3992631},
  {city_name: 'New York', city_population: 8185433},
  {city_name: 'Chicago', city_population: 2655568},
  {city_name: 'China', city_population: 2039471},
];
let bigCitiesAndPopulation = cities.filter(function(e) {
  return e.city_population > 2000000 && e.city_name.startsWith('Chi');
});
console.log(bigCitiesAndPopulation);

Output:

[{
  city_name: "Chicago",
  city_population: 2655568
}, {
  city_name: "China",
  city_population: 2039471
}]

The filter() method returned the array because we used it with the array. Now, we are using it with the array of objects and the filter() function is returning an array of objects.

Alternatively, we can use the filter() method to get the exact results.

let bigCitiesAndPopulation = cities.filter(
    city => city.city_population > 2000000 && city.city_name.startsWith('Chi'));
console.log(bigCitiesAndPopulation);

Output:

[{
  city_name: "Chicago",
  city_population: 2655568
}, {
  city_name: "China",
  city_population: 2039471
}]

The filter method’s implementation without using the built-in method.

let bigCitiesAndPopulation = [];

for (let i = 0; i < cities.length; i++) {
  if (cities[i].city_population > 2000000 &&
      cities[i].city_name.startsWith('Chi')) {
    bigCitiesAndPopulation.push(cities[i]);
  }
}
console.log(bigCitiesAndPopulation);

Output:

[{
  city_name: "Chicago",
  city_population: 2655568
}, {
  city_name: "China",
  city_population: 2039471
}]

We use a for loop that runs until the cities.length-1. Inside the for-loop, we check if the city_population is great than 2000000 and city_name starts with Chi.

If both criteria are satisfied, only then would the city be pushed into the array bigCitiesAndPopulation.

In the upper example, we are supposed to filter the array of objects using two values only.

Suppose we have many values that would be checked to filter the array of objects. In that case, we have to save those values in a separate array.

For example, we have 4 values Biology, Physics, Chemistry, and Arts in filtersArray. We aim to get those objects that have the filtersArray.

var studentCourses = [
  {id: 210, courses: 'Biology Physics Math'},
  {id: 211, courses: 'History Physics ComputerScience'},
  {id: 212, courses: 'Arts Language Biology Chemistry Physics'},
  {id: 213, courses: 'Chemistry Statistics Math'},
  {id: 214, courses: 'Biology Chemistry Physics Arts'},
];

var filtersArray = ['Biology', 'Physics', 'Chemistry', 'Arts'];

var filteredArray = studentCourses.filter(function(element) {
  var courses = element.courses.split(' ');
  return courses
             .filter(function(course) {
               return filtersArray.indexOf(course) > -1;
             })
             .length === filtersArray.length;
});

console.log(filteredArray);

Output:

[{
  courses: "Arts Language Biology Chemistry Physics",
  id: 212
}, {
  courses: "Biology Chemistry Physics Arts",
  id: 214
}]

We get those objects containing all the filtersArray elements. Remember, the objects can have additional courses, but they must hold the element of filterArray to get filtered.

Use the filter() Method to Filter an Array of Objects Dynamically in JavaScript

Dynamically means everything would be decided on run time.

'use strict';
Array.prototype.flexFilter =
    function(criteria) {
  // set variables
  var matchFilters, matches = [], counter;

  // helper function to iterate over the criteria (filter criteria)
  matchFilters =
      function(item) {
    counter = 0
    for (var n = 0; n < criteria.length; n++) {
      if (criteria[n]['Values'].indexOf(item[criteria[n]['Field']]) > -1) {
        counter++;
      }
    }
    // The array's current items satisfies all the filter criteria, if it is
    // true
    return counter == criteria.length;
  }

  // loop through every item of the array
  // and checks if the item satisfies the filter criteria
  for (var i = 0; i < this.length; i++) {
    if (matchFilters(this[i])) {
      matches.push(this[i]);
    }
  }
  // returns a new array holding the objects that fulfill the filter criteria
  return matches;
}

var personData = [
  {id: 1, name: 'John', month: 'January', gender: 'M'},
  {id: 2, name: 'Thomas', month: 'March', gender: 'M'},
  {id: 3, name: 'Saira', month: 'April', gender: 'F'},
  {id: 4, name: 'Daniel', month: 'November', gender: 'M'},
  {id: 5, name: 'Leonardo', month: 'March', gender: 'M'},
  {id: 6, name: 'Jamaima', month: 'April', gender: 'F'},
  {id: 7, name: 'Tina', month: 'December', gender: 'F'},
  {id: 8, name: 'Mehvish', month: 'March', gender: 'F'}
];

var filter_criteria = [
  {Field: 'month', Values: ['March']}, {Field: 'gender', Values: ['F', 'M']}
];
var filtered = personData.flexFilter(filter_criteria);
console.log(filtered);

We use a function to iterate over the filter_criteria to retrieve the matched values.

Every filter criteria would be treated as AND while more than one filter value is taken as OR in a filter field.

Output:

[{
  gender: "M",
  id: 2,
  month: "March",
  name: "Thomas"
}, {
  gender: "M",
  id: 5,
  month: "March",
  name: "Leonardo"
}, {
  gender: "F",
  id: 8,
  month: "March",
  name: "Mehvish"
}]

After checking the filter_criteria, we loop over every array element and assess if it satisfies the filter criteria.

We push into the matches array to meet the filter criteria. Otherwise not.

Once the loop is over, we print the new array that has met the filter_criteria.

Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

Related Article - JavaScript Array