Filter by multiple keys and values, Javascript

javascript filter array multiple values
javascript array.filter multiple arguments
multiple search filter javascript
javascript filter object by key value
javascript filter array of objects by multiple properties
multiple select filter javascript
javascript chain multiple filters
javascript filter nested array of objects

I'm trying to make a filter. The number of filters will change dynamically, a number of keys can be different, and the number of values, too.

This is how data look like:

var data = [
{id: "123", color: "Red", model: "Tesla"}, 
{id: "124", color: "Black", model: "Honda"}, 
{id: "125", color: "Red", model: "Audi"}, 
{id: "126", color: "Blue", model: "Tesla"}]

Filter keys are color and model. But sometimes I will filter only by color or model and sometimes by both. I want to make a function that will cover both cases. Also, a user can choose many values (Tesla, Honda...).

Key can be only color, or only model, or both. Values can look like: only "Red", "Red" and "Blue", or "Red" and "Tesla", or "Red", "Blue" and "Tesla"... Depends on what user choose.

I tried this:

var filtered = [];
data.forEach(item => {
   filterByKey.forEach(key => {
      values.forEach(value => {
         if (item[key] === value) {

Here is JsFiddle

My loop works well when I have one filter key, but it doesn't work well when I have more than one key. Is it a good idea to pass keys and values as an array?

No jQuery please, only pure JavaScript.

You can use filter() with every() and check if value of current object with current key exits in values array using includes()

var data = [{"id":"123","color":"Red","model":"Tesla"},{"id":"124","color":"Black","model":"Honda"},{"id":"125","color":"Red","model":"Audi"},{"id":"126","color":"Blue","model":"Tesla"}]

var keys = ["color", 'model'];
var values = ["Tesla", "Audi", "Red"];

var result = data.filter(function(e) {
  return keys.every(function(a) {
    return values.includes(e[a])


Filter Array of object by multiple keys, Hopefully with pure JS! Edit. Expected value var expected = [ { id  let bigCities = cities.filter(city => city.population > 3000000); console.log(bigCities); JavaScript Array filter() method in detail. The following illustrates the syntax of the filter() method: arrayObject.filter (callback, contextObject); The filter() method creates a new array with all the elements that pass the test implemented by the callback() function.

You could use a combined approach with a seach object which keeps the conditions, like

    model: 'Tesla',                                    // a single value
    color: ['red', 'blue'],                            // a some value
    price: {                                           // a range/interval
        min: 2000, 
        max: 3000
    transmission: v => v.toLowerCase() === 'automatic' // a function

var useConditions = search => a => Object.keys(search).every(k => 
        a[k] === search[k] ||
        Array.isArray(search[k]) && search[k].includes(a[k]) ||
        typeof search[k] === 'object' && +search[k].min <= a[k] &&  a[k] <= +search[k].max ||
        typeof search[k] === 'function' && search[k](a[k])
    data = [{ id: "123", color: "Red", model: "Tesla" }, { id: "124", color: "Black", model: "Honda" }, { id: "125", color: "Red", model: "Audi" }, { id: "126", color: "Blue", model: "Tesla" }],
    filters = { color: ['Red', 'Blue'], model: 'Tesla' };


Filters an array of objects with multiple match-criteria. · GitHub, Where the `filters` argument is an object that contains a `key: string` then it must return a boolean value, which will determine if the item filterArray.test.js. by Alex Permyakov. How to simplify your codebase with map(), reduce(), and filter() in JavaScript Photo by Anders Jildén on Unsplash. When you read about Array.reduce and how cool it is, the first and sometimes the only example you find is the sum of numbers.

You can use Array.prototype.filter() where the function to test each element of the array is:

el => !!filterBy.toString().match(new RegExp(`(?=.*${el.color})(?=.*${el.model})`))

It consist of a regular expression new RegExp(`(?=.*${el.color})(?=.*${el.model})`)) that match to strings color and model in another string filterBy.toString()

var data = [{id: "123", color: "Red", model: "Tesla"}, {id: "124", color: "Black", model: "Honda"}, {id: "125", color: "Red", model: "Audi"}, {id: "126", color: "Blue", model: "Tesla"}],
    filterBy = ['Tesla', 'Audi', 'Red', 'Black'],
    result = data.filter(el => !!filterBy.toString().match(new RegExp(`(?=.*${el.color})(?=.*${el.model})`)));


Creating a Multi-Filter Function to Filter Out Multiple Attributes Using , Customers can click on any tags, my filter function will render only products What is .filter() in Javascript? The function will search through the state, find the key called color and change the boolean value to true or false  If you’re starting in JavaScript, maybe you haven’t heard of .map(), .reduce(), and .filter().For me, it took a while as I had to support Internet Explorer 8 until a couple years ago.

Is this what you want to achieve?

var data = [
  {id: "123", color: "Red", model: "Tesla"}, 
  {id: "124", color: "Black", model: "Honda"}, 
  {id: "125", color: "Red", model: "Audi"}, 
  {id: "126", color: "Blue", model: "Tesla"}

var allowedColors = ["Red", "Blue"];
var allowedModels = ["Tesla", "Audi"];

function filter (cars, colors, models) {
  return cars.filter(function (car) {
    return colors.indexOf(car.color) !== -1 && // check if the car's color is allowed
      models.indexOf(car.model) !== -1;        // check if the car's model is allowed

var filtered = filter(data, allowedColors, allowedModels);

JavaScript: manipulating objects with Object.keys() –, How would you do this in basic JS? Array filter? Array map? Array reduce? None of these? I was looping the objects and setting the visible property of the object to   Object.keys, values, entries. For plain objects, the following methods are available: Object.keys(obj) – returns an array of keys. Object.values(obj) – returns an array of values. Object.entries(obj) – returns an array of [key, value] pairs. Please note the distinctions (compared to map for example):

Filtering is native in JS, try this:

data.filter(item => item.color==='Red');
// or in the old fashion 
data.filter(function(item){ return item.color==='Red';} );

Filtering an array of JSON objects by multiple properties : javascript, var matchingKeys = myKeys.filter(function(key){ return key.indexOf(myString) !== -1 });. Get the value using myObject[matchingKey] . Processing  Filtering out all small values The following example uses filter () to create a filtered array that has all elements with values less than 10 removed. function isBigEnough(value) { return value >= 10 } let filtered = [12, 5, 8, 130, 44].filter(isBigEnough) // filtered is [12, 130, 44] Find all prime numbers in an array

Quickly filter an object by keys, Im trying to filtering multidimensional object using lodash filter object Below are my sample object to filter data 0 details Java 8 – Filter Map by both Keys and Values. In this example we are filtering a Map by keys and values both. When we filter a Map like this we are joining both the conditions by AND (&&) logical operator. You can also place both the conditions in the single filter() method and join them using any logical operator such as OR (||), AND(&&) or

Lodash multiple key with multiple array of values filter , This tutorial shows you how to use the JavaScript array filter method to filter loop and test if the value of the population property satisfies the condition, like this:. raise ValueError("multiple values for unique attribute %r: %r" % (key, values)) ValueError: multiple values for unique attribute 'typeOfLevel': ['hybrid', 'cloudBase', 'unknown', 'cloudTop'] I've tried with both grib1 and grib2 file types and it seems the formatting is incorrect for all the files I've tried. Any suggestions? 👍

JavaScript Array Filter: Filtering Array Elements Based on a Test , I'm trying to do a fuzzy search, which I've partially achieved on the slug and title fields it's just this value field in the headings array that's driving  Not necessarily an array. And the standard iteration for map returns same key/value pairs as map.entries(). So we get a plain object with same key/values as the map. Set. A Set is a special type collection – “set of values” (without keys), where each value may occur only once. Its main methods are:

  • This is exactly what I was looking for! Thanks!
  • Hey Nenad, function works great, but working with it I figured out one case we missed. That case is when same value repeats for values. Color and model have same value. It's a stupid example, but let's say a color is "Red" and model is "Red", too. Should I maybe pass key and values together as an object? What do you suggest? Thanks!
  • Hey, Nenad? Can you help me, please?
  • @snoopy25 I don't see the problem it will return it.
  • this should be the accepted answer, simple and amazing ! thanks
  • I think he might want to be able to set models or colors to null, with the meaning "all".
  • This works well only for this case, but if I want to group filter only colors or only models this doesn't work.