Filter Array Not in Another Array

老子叫甜甜 提交于 2019-12-18 18:58:10

问题


Need to filter one array based on another array. Is there a util function in knock out ? else i need to go with 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)

output:

[{
    "visible": "true",
    "id": 1
}, {
    "Name": "Test3",
    "id": 4
}];

回答1:


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

With newer ES syntax and APIs, it becomes simpler:

const arr = obj1.filter(i => obj2.includes(i.id))



回答2:


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.

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


来源:https://stackoverflow.com/questions/33577868/filter-array-not-in-another-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!