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]
Thank you very much.
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.
});
In a 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 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));
Thanks Second Rikhdo full code:
var a = [1,2,3,4,5];
var b = [4,5,6,7,8,9];
var new_array = a.filter(function(item) {
return b.indexOf(item) < 0; // Returns true for items not found in b.
});
alert(new_array);
// results: array[1,2,3]
Demo: https://jsfiddle.net/cmoa7Lw7/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With