[英]Filtering an array with an array of values
I have 2 arrays and i'd like to filter one array with the other.我有 2 个 arrays ,我想用另一个过滤一个数组。 Eg if array1 includes any of the values in array2, they should be returned.
例如,如果 array1 包含 array2 中的任何值,则应返回它们。
The two arrays are:两个 arrays 是:
const array1 = [a, b, c, d]
The other array, which should be filtered where 'id' is equal to any of the values in array1 is:另一个数组,应在“id”等于 array1 中的任何值的情况下进行过滤:
const array2 = [
{
id: b
title: title1
},
{
id: d
title: title2
},
{
id: f
title: title3
}
]
The easiest way is to use two for-loops.最简单的方法是使用两个 for 循环。 Possible not the fastest approach.
可能不是最快的方法。
res = [];
for (var i = 0;i<array1.length;i++) {
for (var j = 0;j<array2.length;j++) {
if (array1[i] == array2[j].id) {
res.push(array2[j]);
break;
}
}
}
You could use Array.prototype.filter() and Array.prototype.indexOf() :您可以使用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;
});
Adding this missing ''
, You can use filter
and includes
methods of Array.添加这个缺失
''
,您可以使用filter
并includes
Array 的方法。
const array1 = ['a', 'b', 'c', 'd'];
const array2 = [
{
id: 'b',
title: 'title1'
},
{
id: 'd',
title: 'title2'
},
{
id: 'f',
title: 'title3'
}
]
const result = array2.filter(({id}) => array1.includes(id));
console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.