Skip to content

Instantly share code, notes, and snippets.

@Goloburda
Last active April 30, 2020 16:06
Show Gist options
  • Save Goloburda/7279dce53a51e44553b91b94f6018d1b to your computer and use it in GitHub Desktop.
Save Goloburda/7279dce53a51e44553b91b94f6018d1b to your computer and use it in GitHub Desktop.
[JavaScript] Filter array of objects by multiple params.
const arr = [
{name: "Mikita", age: 1, city: "Hrodna"},
{name: "Martin", age: 2, city: "Berlin"},
{name: "Nikita", age: 3, city: "Hrodna"},
{name: "Nikita", age: 4, city: "Hrodna"},
{name: "Sasha", age: 2, city: "Minsk"},
{name: "Sasha", age: 2, city: "Paris"},
{name: "Sasha", age: 2, city: "Hrodna"},
{name: "Martin", age: 2, city: "Berlin"},
{name: "Martin", age: 2, city: "London"},
{name: "Mikita", age: 2, city: "London"},
]
const filters = { city: ["London", "Hrodna"]}
const result = arr.filter(item => {
let shouldReturn = false;
for (const filter in filters) {
if (Array.isArray(filters[filter])) {
if (filters[filter].indexOf(item[filter]) >= 0) {
shouldReturn = true;
} else {
return undefined;
}
} else {
if (item[filter] === filters[filter]) {
shouldReturn = true;
} else {
shouldReturn = false;
return undefined;
}
}
}
return shouldReturn && item
})
console.log(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment