我想了解从另一个数组的所有元素中过滤一个数组的最佳方法。我尝试了过滤功能,但它不来我如何给它的值,我想删除。喜欢的东西:
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的人有用。如果答案勾选“好”,事情就简单多了。
这完全取决于数组的类型。
对于简单的数组,比如字符串数组。你可以像@Redu和@Hugolpz指出的那样使用下面的代码
var arr1 = [1,2,3,4],
arr2 = [2,4],
res = arr1.filter(item => !arr2.includes(item));
console.log(res);
然后,对于更复杂的数组过滤器,比如从另一个对象数组中过滤一个对象数组,您可以使用下面的代码
function filterArray(arr1, arr2) {
return arr1.filter(item1 => !arr2.some(item2 => item1.id === item2.id));
}
OR
function filterArray(arr1, arr2) {
const set = new Set(arr2.map(item => item.id));
return arr1.reduce((filtered, item) => {
if (!set.has(item.id)) {
filtered.push(item);
}
return filtered;
}, []);
}
这两种方法都是有效的,即使使用大型数组也能很好地工作。但是,如果您有大量数据,则使用性能更好的数据结构(如Map或HashSet)可能会更优。
Map
function filterArray(arr1, arr2) {
const map = new Map(arr2.map(item => [item.id, item]));
return arr1.filter(item => !map.has(item.id));
}
Hashset
function filterArray(arr1, arr2) {
const set = new Set(arr2.map(item => item.id));
return arr1.filter(item => !set.has(item.id));
}
你可以写一个泛型的filterByIndex()函数,并在TS中使用类型推断来省去回调函数的麻烦:
假设你有一个数组[1,2,3,4],你想用[2,4]数组中指定的下标来过滤()。
var filtered = [1,2,3,4,].filter(byIndex(element => element, [2,4]))
byIndex函数需要元素函数和数组,如下所示:
byIndex = (getter: (e:number) => number, arr: number[]) => (x: number) => {
var i = getter(x);
return arr.indexOf(i);
}
结果就是这样
filtered = [1,3]
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演示不同的对象数组