如何从另一个数组的所有元素过滤数组

如何从另一个数组的所有元素过滤数组

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

问题描述



我想了解从另一个的所有元素过滤数组的最佳方法。我试着用过滤器的功能,但它没有来找我如何给它我想要删除的值。
类似:

  var array = [1,2,3,4]; 
var anotherOne = [2,4];
var filteredArray = array.filter(myCallback);
// filteredArray现在应该是[1,3]


函数myCallBack(){
return element! filteredArray;
//显然不能工作,因为我们没有参考文献<,<
}

如果过滤器函数不是有用的,那么您将如何实现?

编辑:我检查了可能的重复问题,它可以很容易理解JavaScript的人有用。您可以使用filter()函数的this参数来避免这个问题。

解决方案


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



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

in case the filter function is not usefull, how would you implement this ?
Edit: 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.

解决方案

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

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

08-14 17:32