Javascript filter array multiple values – example
Posted on: February 11, 2021 by Deven
In JavaScript to filter multiple values in an Array, you can use filter() array function.
JavaScript filter multiple values in an Array
consider the example below:
var allPersons: Array<Person>;
var found = allPersons.filter(person => {
return name === person.name || gender === person.gender || hair === person.hair || height === person.height;
});
In the above code, we can filter an array of objects by testing whether the properties match a certain set of criteria. We can also use template object for filtering:
function findByTemplate(allPersons: Array<Person>, template: any) {
return allPersons.filter(person => {
return Object.keys(template).every(propertyName => person[propertyName] === template[propertyName]);
});
}
We can use above code like below:
var found = findByTemplate(allPersons, {name: "John", gender: "Male"});
var found = findByTemplate(allPersons, {name: "John"});
var found = findByTemplate(allPersons, {name: "John", gender: "Male", hair: "Red", height: '160 cm'});
Share on social media
//