过滤不在另一个阵列中的阵列 [英] Filter Array Not in Another Array
问题描述
需要根据另一个数组过滤一个数组.敲除功能中是否有util函数?否则我需要使用javascript
Need to filter one array based on another array. Is there a util function in knock out ? else i need to go with javascript
第一:
var obj1 = [{
"visible": "true",
"id": 1
}, {
"visible": "true",
"id": 2
}, {
"visible": "true",
"id": 3
}, {
"Name": "Test3",
"id": 4
}];
第二个:
var obj2 = [ 2,3]
现在我需要基于obj2过滤obj1并从obj2中返回不在上述数据中的obj2 omittng 2,3中的项目(与对象1 Id 进行比较)
Now i need to filter obj1 based on obj2 and return items from obj1 that are not in obj2 omittng 2,3 in the above data (Comparison on object 1 Id)
输出:
[{
"visible": "true",
"id": 1
}, {
"Name": "Test3",
"id": 4
}];
推荐答案
您可以简单地使用filter
在obj1
中运行,并在obj2
上使用indexOf
来查看它是否存在.如果值不在数组中,则indexOf
返回-1
,并且当回调返回true
时filter
包括该项.
You can simply run through obj1
using filter
and use indexOf
on obj2
to see if it exists. indexOf
returns -1
if the value isn't in the array, and filter
includes the item when the callback returns true
.
var arr = obj1.filter(function(item){
return obj2.indexOf(item.id) === -1;
});
使用更新的ES语法和API,它变得更加简单:
With newer ES syntax and APIs, it becomes simpler:
const arr = obj1.filter(i => obj2.includes(i.id))
这篇关于过滤不在另一个阵列中的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!