-3

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' ]
Andy
  • 61,948
  • 13
  • 68
  • 95
Dinesh kapri
  • 68
  • 1
  • 2
  • 9
  • this helps? https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript – cmgchess Mar 24 '22 at 19:59

2 Answers2

2

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 );
PeterKA
  • 24,158
  • 5
  • 26
  • 48
1

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);
Mushroomator
  • 6,516
  • 1
  • 10
  • 27