javascript filter array of objects by multiple values code example
Example 1: js filter array of objects by value
var heroes = [
{name: “Batman”, franchise: “DC”},
{name: “Ironman”, franchise: “Marvel”},
{name: “Thor”, franchise: “Marvel”},
{name: “Superman”, franchise: “DC”}
];
var marvelHeroes = heroes.filter(function(hero) {
return hero.franchise == “Marvel”;
});
// [ {name: “Ironman”, franchise: “Marvel”}, {name: “Thor”, franchise: “Marvel”} ]
Example 2: filter out object in array using two arguments
var arr= [{id: "123", name: "Faa"},
{id: "123", name: "Bar"},
{id: "345", name: "Foo"},
{id: "678", name: "FaaBar"}
];
var name = 'FaaBar';
var id = '678';
arr = arr.filter(function(elem) {
//return false for the element that matches both the name and the id
return !(elem.id == id && elem.name == name)
});
Example 3: javascript filter array multiple values
// use .filter and write multiple validations in the callback function
let numbers = [3, 7, 2, 15, 4, 9, 21, 14];
let filteredNumbers = numbers.filter(function (currentElement) {
if (currentElement > 3 && currentElement < 17) {
return true;
}
});
console.log(filteredNumbers);
Example 4: javascript find object in array by multiple property values
let serverProposal = lobby.proposals.find( (p) => p.author == userID && p.isSubmitted == false);