如何从另一个数组的所有元素中过滤一个数组 [英] How to filter an array from all elements of another array

查看:35
本文介绍了如何从另一个数组的所有元素中过滤一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我想了解从另一个数组的所有元素中过滤一个数组的最佳方法.我尝试使用过滤器功能,但我不知道如何给它我想要删除的值.
类似的东西:


I'd like to understand the best way to filter an array from all elements of another one. I tried with the filter function, but it doesn't come to me how to give it the values i want to remove.
Something Like:

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的人很有用.检查为好的答案使事情变得容易.

in case the filter function is not usefull, how would you implement this ?
i checked the possible duplicate question, and it could be useful for those who understand javascript easily. The answer checked as good makes things easy.

推荐答案

您可以使用 filter() 函数的 this 参数来避免存储过滤器数组在一个全局变量中.

You can use the this parameter of the filter() function to avoid to store your filter array in a global variable.

var filtered = [1, 2, 3, 4].filter(
    function(e) {
      return this.indexOf(e) < 0;
    },
    [2, 4]
);
console.log(filtered);

这篇关于如何从另一个数组的所有元素中过滤一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆