从数组javascript中删除元素(相反的交集) [英] removes elements from array javascript (contrary intersection)
本文介绍了从数组javascript中删除元素(相反的交集)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
昨天,我提出了这个问题从数组javascript中删除元素
但是我误解了,我的解释和示例都是关于两个数组之间的交集.
我想问的是如何删除数组中其他数组中不存在的元素.
示例:
Yesterday nigth I maked this question Delete elements from array javascript
But I mistook, my explanation and my example were about an intersection between two arrays.
What I wanted to ask is about how remove elements on array that doesn´t exist on other array.
Example:
Array A=> [a, b, c, d]
Array B=> [b, d, e]
Array C= removeElementsNotIn(A, B);
Array C (after function)-> [a,c]
非常感谢您.
推荐答案
您可以使用.filter()
有选择地删除未通过测试的项目.
You can use .filter()
to selectively remove items that don't pass a test.
var c = a.filter(function(item) {
return b.indexOf(item) < 0; // Returns true for items not found in b.
});
在函数中:
function removeElementsNotIn(a, b) {
return a.filter(function(item) {
return b.indexOf(item) < 0; // Returns true for items not found in b.
});
}
var arrayC = removeElementsNotIn(arrayA, arrayB);
如果您想真正(仅高级),可以创建一个返回过滤功能的函数,如下所示:
If you want to get really fancy (advanced only), you can create a function that returns the filtering function, like so:
function notIn(array) {
return function(item) {
return array.indexOf(item) < 0;
};
}
// notIn(arrayB) returns the filter function.
var c = arrayA.filter(notIn(arrayB));
这篇关于从数组javascript中删除元素(相反的交集)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文