Remove elements from javascript array (opposite intersection)
Yesterday I resolved this question Remove elements from javascript array
But I was wrong, my explanation and my example were about intersection of two arrays.
I wanted to ask how to remove elements in an array that do not exist in another array.
Example :
Array A=> [a, b, c, d]
Array B=> [b, d, e]
Array C= removeElementsNotIn(A, B);
Array C (after function)-> [a,c]
Many thanks.
+3
source to share
3 answers
You can use .filter()
to selectively remove items that fail the test.
var c = a.filter(function(item) {
return b.indexOf(item) < 0; // Returns true for items not found in b.
});
In function:
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 a filter function, like this:
function notIn(array) {
return function(item) {
return array.indexOf(item) < 0;
};
}
// notIn(arrayB) returns the filter function.
var c = arrayA.filter(notIn(arrayB));
+3
source to share
a1 = ['s1', 's2', 's3', 's4', 's5'];
a2 = ['s4', 's5', 's6'];
a3 = [];
function theFunction(ar1, ar2) {
var ar3 = [];
for (var i = 0; i < a1.length; i++) {
if (ar2.indexOf(ar1[i]) != -1) {
ar3.push(ar1[i]);
}
}
return ar3;
}
a3 = theFunction(a1, a2);
document.getElementById('out').innerHTML = a3.toString();
<div id="out"></div>
+1
source to share