Filtering An Array Of Objects With Multiple Filter Conditions
Lets assume I have an array of objects: let users = [{ name: 'Mark', location: 'US', job: 'engineer' }, { name: 'Mark', location: 'US', job: 'clerk' }, { name: 'Angela', lo
Solution 1:
Use Object.entries()
on filters
to get an array of [key, values]
pairs. Iterate the pairs with Array.every()
, and check that each pair includes the value of the current object.
constfn = (arr, filters) => {
const filtersArr = Object.entries(filters)
return arr.filter(o =>
filtersArr.every(([key, values]) =>
values.includes(o[key])
)
)
}
const users = [{"name":"Mark","location":"US","job":"engineer"},{"name":"Mark","location":"US","job":"clerk"},{"name":"Angela","location":"Europe","job":"pilot"},{"name":"Matthew","location":"US","job":"engineer"}]
const filters = {
name: ["Mark", "Matthew"],
location: ["US"],
job: ["engineer"]
}
const result = fn(users, filters)
console.log(result)
One caveat of using Array.includes()
is that differences in case would provide a false
answer (Engineer and engineer in this case). To solve that convert the current word to a RegExp, with the Case-insensitive search flag (i
), and check using Array.some()
if it fits any of the words in the array.
constfn = (arr, filters) => {
const filtersArr = Object.entries(filters)
return arr.filter(o =>
filtersArr.every(([key, values]) => {
const pattern = newRegExp(`^${o[key]}$`, 'i')
return values.some(v => pattern.test(v))
})
)
}
const users = [{"name":"Mark","location":"US","job":"engineer"},{"name":"Mark","location":"US","job":"clerk"},{"name":"Angela","location":"Europe","job":"pilot"},{"name":"Matthew","location":"US","job":"engineer"}]
const filters = {
name: ["Mark", "Matthew"],
location: ["US"],
job: ["Engineer"]
}
const result = fn(users, filters)
console.log(result)
Solution 2:
You can loop over the entries of the filters object and ensure that the value of each key is one of the allowed ones.
let users = [{name:"Mark",location:"US",job:"Engineer"},{name:"Mark",location:"US",job:"clerk"},{name:"Angela",location:"Europe",job:"pilot"},{name:"Matthew",location:"US",job:"Engineer"}];
const filters = {
name: ["Mark", "Matthew"],
location: ["US"],
job: ["Engineer"]
};
const res = users.filter(o =>Object.entries(filters).every(([k,v])=>v.includes(o[k])));
console.log(res);
Post a Comment for "Filtering An Array Of Objects With Multiple Filter Conditions"