Filter by multiple keys and values, 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])
})
})
console.log(result);
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})`)));
console.log(result);
And also, you can combine Array.prototype.filter() and Array.prototype.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"}],
filterBy = ['Tesla', 'Audi', 'Red', 'Black'],
result = data.filter(el => filterBy.includes(el.model) && filterBy.includes(el.color));
console.log(result);
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' };
console.log(data.filter(useConditions(filters)));