将数组过滤到另一个数组

时间:2018-06-10 13:44:34

标签: javascript jquery

我有2个像这样的阵列......

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);

此代码返回'undefined'。所以基本上我试图根据另一个数组中的值过滤数组。

有人可以告诉我我做错了什么吗?感谢

我的预期输出是一系列对象,如下所示...

[
{name: "Thor", franchise: "Marvel"},
{name: "Superman", franchise: "DC"}
];

我见过类似问题here,但该解决方案对我不起作用......

2 个答案:

答案 0 :(得分:1)

应该只返回 stars.indexOf(item.name) !== -1 ;

<强>样本

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用includes来确定数组是否包含某个元素

&#13;
&#13;
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);
&#13;
&#13;
&#13;

更短的代码:

&#13;
&#13;
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 );
&#13;
&#13;
&#13;

Doc:includes()