Home > Mobile >  Best way to remove elements from an array1 which are present in array2 Javascript?
Best way to remove elements from an array1 which are present in array2 Javascript?

Time:03-25

Let's say we have the following JavaScript array

var array1 = ['Teams' , 'Chat' , 'Zoom' , 'Slack' ] 

var array2 = [ 'Zoom' , 'Chat'] 

How to make a new array in which only those elements of array1 present which are not in array2?

New Array should look like

new_array = [ 'Teams' , 'Slack' ]

CodePudding user response:

Use Array#filter() method:

const newArray = array1.filter(e => !array2.includes(e));

DEMO

const array1 = ['Teams' , 'Chat' , 'Zoom' , 'Slack' ];
const array2 = [ 'Zoom' , 'Chat'];

const newArray = array1.filter(e => !array2.includes(e));

console.log( newArray );

CodePudding user response:

This will run in O(n) time in best, worst and average case for n elements in array1 as the lookup in the Set happens in O(1) and will return the correct result.

Using Array#includes() will result in a worst case runtime of O(n * m) for n elements in array1 and m elements in array2 when all elements in array1 and array2 are different. And even if they are not you would on average need m / 2 steps to find a match in array2 using Array#includes(), which would still result in an average case runtime of O(n * m).

const array1 = ['Teams' , 'Chat' , 'Zoom' , 'Slack' ] 

const array2 = [ 'Zoom' , 'Chat']

// Create a Set for lookups in O(1); Creation will take O(n).
const array2Set = new Set(array2);
// Only return elements that are not in the Set in O(n) 
const newArray = array1.filter(item => !array2Set.has(item))

// print result
console.log(newArray);

  • Related