Javascript 过滤器阵列不在另一个阵列中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33577868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter Array Not in Another Array
提问by Peru
Need to filter one array based on another array. Is there a util function in knock out ? else i need to go with javascript
需要根据另一个数组过滤一个数组。击倒中是否有 util 函数?否则我需要使用 javascript
First :
第一的 :
var obj1 = [{
"visible": "true",
"id": 1
}, {
"visible": "true",
"id": 2
}, {
"visible": "true",
"id": 3
}, {
"Name": "Test3",
"id": 4
}];
Second :
第二 :
var obj2 = [ 2,3]
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)
现在我需要根据 obj2 过滤 obj1 并从 obj1 返回上面数据中不在 obj2 omitng 2,3 中的项目(对象 1 Id 的比较)
output:
输出:
[{
"visible": "true",
"id": 1
}, {
"Name": "Test3",
"id": 4
}];
回答by Joseph
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
.
您可以简单地运行obj1
usingfilter
和 use indexOf
onobj2
来查看它是否存在。indexOf
返回-1
如果该值不是在阵列中,并且filter
包括所述项目时回调返回true
。
var arr = obj1.filter(function(item){
return obj2.indexOf(item.id) === -1;
});
With newer ES syntax and APIs, it becomes simpler:
使用更新的 ES 语法和 API,它变得更简单:
const arr = obj1.filter(i => !obj2.includes(i.id))
回答by Marwan Sulaiman
To create your output array, create a function that will iterate through obj1 and populate a new array based on whether the id of every obj in the iteration exists in obj2.
要创建您的输出数组,请创建一个函数,该函数将遍历 obj1 并根据迭代中每个 obj 的 id 是否存在于 obj2 中来填充一个新数组。
var obj1 = [{
"visible": "true",
"id": 1
}, {
"visible": "true",
"id": 2
}, {
"visible": "true",
"id": 3
}, {
"Name": "Test3",
"id": 4
}];
var obj2 = [2,3]
var select = function(arr) {
var newArr = [];
obj1.forEach(function(obj) {
if obj2.indexOf(obj.id) !== -1 {
newArr.push(obj)
};
};
return newArr;
};