Nithin
Nithin

Reputation: 1477

Remove an array of elements from another array

I have an array array1 = [1,2,3,4,5,6] and another array array2 = [4,5].

The objective is to remove array2's elements from array1 with the least time complexity.

Final array is [1,2,3,6]

I know we can do something like this for every element

function remove(array, element) {
    return array.filter(e => e !== element);
}

let array1 = [1,2,3,4,5,6];
array2 = [4,5];
array2.forEach(el => {
    array1 = remove(array1, el);
});

How do i make it better?

Upvotes: 1

Views: 147

Answers (2)

Constantin Guidon
Constantin Guidon

Reputation: 1892

Simpler and cleaner

const arr1 = [1,2,3,4]
const arr2 = [3,4]
const newArray = arr1.filter( x => !arr2.includes(x))
console.log(newArray)

Upvotes: 2

Houssein Zouari
Houssein Zouari

Reputation: 722

I have two solutions for you :

var arr1 = [ 1, 2,3 ];
var arr2 = [1,2,4 ];
var result = arr1.filter(o1 => arr2.filter(o2 => o2 === o1).length === 0);
console.log(result);

Or you can use difference of Loadash

Upvotes: 2

Related Questions