Reputation: 906
I have 2 arrays like this ...
var heroes = [{
name: "Batman",
franchise: "DC"
},
{
name: "Ironman",
franchise: "Marvel"
},
{
name: "Thor",
franchise: "Marvel"
},
{
name: "Superman",
franchise: "DC"
}
];
var stars = ["Thor", "Superman"];
var marvelHeroes = heroes.filter(function(hero) {
return stars.indexOf(hero.name) >= 0;
});
console.log(marvelHeroes);
This code is returning 'undefined'. So essentially I am trying to filter an array against values in another array.
Can someone please advise what am I doing wrong ? Thanks
My expected output is an array of objects like the following ...
[
{name: "Thor", franchise: "Marvel"},
{name: "Superman", franchise: "DC"}
];
I have seen a similar question here, but that solution is not working for me ...
Upvotes: 1
Views: 103
Reputation: 222572
It should be just return stars.indexOf(item.name) !== -1 ;
DEMO
var heroes = [
{name: "Batman", franchise: "DC"},
{name: "Ironman", franchise: "Marvel"},
{name: "Thor", franchise: "Marvel"},
{name: "Superman", franchise: "DC"}
];
var stars = ["Thor","Superman"];
var filtered = heroes.filter(function(item) {
return stars .indexOf(item.name) !== -1 ;
});
console.log(filtered);
Upvotes: 1
Reputation: 26844
You can use includes
to determine whether an array includes a certain element
var heroes = [{name:"Batman",franchise:"DC"},{name:"Ironman",franchise:"Marvel"},{name:"Thor",franchise:"Marvel"},{name:"Superman",franchise:"DC"}];
var stars = ["Thor", "Superman"];
var marvelHeroes = heroes.filter(function(hero) {
return stars.includes(hero.name);
});
console.log(marvelHeroes);
For shorter code:
var heroes = [{name:"Batman",franchise:"DC"},{name:"Ironman",franchise:"Marvel"},{name:"Thor",franchise:"Marvel"},{name:"Superman",franchise:"DC"}]
var stars = ["Thor", "Superman"];
var marvelHeroes = heroes.filter(o => stars.includes(o.name));
console.log( marvelHeroes );
Doc: includes()
Upvotes: 0