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

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的人有用。如果答案勾选“好”,事情就简单多了。


当前回答

OA也可以在ES6中实现,如下所示

ES6:

 const filtered = [1, 2, 3, 4].filter(e => {
    return this.indexOf(e) < 0;
  },[2, 4]);

其他回答

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

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

您可以使用过滤器,然后为过滤器函数使用过滤数组的约简,当它找到匹配时检查并返回true,然后在返回(!)时反转。filter函数对数组中的每个元素调用一次。在你的文章中,你没有对函数中的任何元素进行比较。

Var a1 = [1,2,3,4], A2 = [2,3]; Var filter = a1.filter(函数(x) { 返回! a2。Reduce(函数(y, z) { 返回x == y || x == z || y == true; }) }); document . write(过滤);

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

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)) =>权衡…:))

函数的arr (arr1 arr2) { 函数filt(价值){ 返回arr2.indexOf(value) == -1; } 返回arr1.filter (filt) } . getelementbyid (p)。innerHTML = arr([1,2,3,4],[2,4]) < p id = p > < / p >

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

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