我想了解从另一个数组的所有元素中过滤一个数组的最佳方法。我尝试了过滤功能,但它不来我如何给它的值,我想删除。喜欢的东西:

var array = [1,2,3,4];
var anotherOne = [2,4];
var filteredArray = array.filter(myCallback);
// filteredArray should now be [1,3]


function myCallBack(){
    return element ! filteredArray; 
    //which clearly can't work since we don't have the reference <,< 
}

如果过滤器函数没有用处,您将如何实现它? 编辑:我检查了可能的重复问题,这可能对那些容易理解javascript的人有用。如果答案勾选“好”,事情就简单多了。


当前回答

/* Here's an example that uses (some) ES6 Javascript semantics to filter an object array by another object array. */ // x = full dataset // y = filter dataset let x = [ {"val": 1, "text": "a"}, {"val": 2, "text": "b"}, {"val": 3, "text": "c"}, {"val": 4, "text": "d"}, {"val": 5, "text": "e"} ], y = [ {"val": 1, "text": "a"}, {"val": 4, "text": "d"} ]; // Use map to get a simple array of "val" values. Ex: [1,4] let yFilter = y.map(itemY => { return itemY.val; }); // Use filter and "not" includes to filter the full dataset by the filter dataset's val. let filteredX = x.filter(itemX => !yFilter.includes(itemX.val)); // Print the result. console.log(filteredX);

其他回答

var array = [1,2,3,4];
var anotherOne = [2,4];
var filteredArray = array.filter(myCallBack);

function myCallBack(el){
  return anotherOne.indexOf(el) < 0;
}

在回调中,检查数组的每个值是否在另一个数组中

https://jsfiddle.net/0tsyc1sx/

如果使用lodash.js,请使用_.difference

filteredArray = _.difference(array, anotherOne);

Demo

如果你有一个对象数组:

var array = [{id :1, name :"test1"},{id :2, name :"test2"},{id :3, name :"test3"},{id :4, name :"test4"}];

var anotherOne = [{id :2, name :"test2"}, {id :4, name :"test4"}];

var filteredArray  = array.filter(function(array_el){
   return anotherOne.filter(function(anotherOne_el){
      return anotherOne_el.id == array_el.id;
   }).length == 0
});

对象的演示数组

用lodash演示不同的对象数组

下面是当数组中的项是对象时的操作方法。

其思想是使用map函数在内部数组中查找仅包含键的数组

然后检查这些键的数组是否包含外层数组中的特定元素键。

const existsInBothArrays = array1.filter((element1) =>
    array2.map((element2) => element2._searchKey).includes(element1._searchKey),
  );

你可以设置过滤器函数来遍历“过滤器数组”。

var arr = [1, 2, 3 ,4 ,5, 6, 7];
var filter = [4, 5, 6];

var filtered = arr.filter(
  function(val) {
    for (var i = 0; i < filter.length; i++) {
      if (val == filter[i]) {
        return false;
      }
    }
    return true;
  }
); 

我只是想给你一个额外的解决方案…

const arr1 = [1,2,3,4];
const arr2 = [2,4];
const container = arr2.reduce((res,item) => {
 res[item] = true;
 return res;
}, {});
const result = arr1.filter(item => !container[item]);

关于上述代码的时间复杂度:O(n)。 而且,……我们需要更多的空间(空间复杂度O(n)) =>权衡…:))

如果你需要比较一个对象数组,这在所有情况下都适用:

let arr = [{ id: 1, title: "title1" },{ id: 2, title: "title2" }]
let brr = [{ id: 2, title: "title2" },{ id: 3, title: "title3" }]

const res = arr.filter(f => brr.some(item => item.id === f.id));
console.log(res);