Last active
April 30, 2020 16:06
-
-
Save Goloburda/7279dce53a51e44553b91b94f6018d1b to your computer and use it in GitHub Desktop.
[JavaScript] Filter array of objects by multiple params.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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