首页 > 解决方案 > 使用值数组过滤数组

问题描述

我有 2 个数组,我想用另一个数组过滤一个数组。例如,如果 array1 包含 array2 中的任何值,则应返回它们。

这两个数组是:

const array1 = [a, b, c, d]

另一个数组,应在“id”等于 array1 中的任何值的情况下进行过滤:

const array2 = [
{
   id: b
   title: title1
},
{
   id: d
   title: title2
},
{
   id: f
   title: title3
}
]

标签: javascriptarrays

解决方案


您可以使用Array.prototype.filter()Array.prototype.indexOf()

const array1 = ['a', 'b', 'c', 'd'];

const array2 = [{
   id: 'b',
   title: 'title1'
}, {
   id: 'd',
   title: 'title2'
}, {
   id: 'f',
   title: 'title3'
}];

const result = array2.filter(function(x){
    return array1.indexOf(x.id) !== -1;
});

推荐阅读