简体   繁体   English

过滤器阵列不在另一个阵列中

[英]Filter Array Not in Another Array

Need to filter one array based on another array.需要根据另一个数组过滤一个数组。 Is there a util function in knock out ?击倒中是否有 util 函数? else i need to go with javascript否则我需要使用 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
}];

You can simply run through obj1 using filter and use indexOf on obj2 to see if it exists.您可以使用filter简单地运行obj1并在obj2上使用indexOf来查看它是否存在。 indexOf returns -1 if the value isn't in the array, and filter includes the item when the callback returns true .如果该值不在数组中,则indexOf返回-1 ,并且当回调返回truefilter包括该项目。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM