Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removes elements from array javascript (contrary intersection)

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.

like image 618
Eloy Fernández Franco Avatar asked Apr 18 '15 09:04

Eloy Fernández Franco


2 Answers

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)); 
like image 175
Madara's Ghost Avatar answered Sep 21 '22 09:09

Madara's Ghost


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/

like image 20
Basem Avatar answered Sep 24 '22 09:09

Basem