0

I have two arrays:

const arr1 = ['abc', 'def', 'ghi', 'jkl'];
const arr2 = ['123', 'abc', 'jkl', '456', '789'];

What would be the cleanest way to return arr2 without the elements of arr1?

I guess arr2.filter(x => arr1.indexOf(x) < 0) would work, but is there a cleaner way?

James Burani
  • 149
  • 1
  • 8
  • For this size array, there's nothing that will really be better than what you have. For larger arrays, you may want to put `arr1` into a Set because then all the look ups on what is in `arr1` will go a lot faster. But, that's not worth it for small arrays. – jfriend00 Jun 01 '20 at 03:53
  • `arr2.filter(x => arr1.indexOf(x) < 0)` not clean enough for you? – Yousaf Jun 01 '20 at 03:54
  • As @jfriend00 said, +1 more point for the large arrays ==> `sort arrays before` doing the operation. And break looping after reaching the largest item in the array. – Dipak Jun 01 '20 at 04:06

4 Answers4

1

You can do a very slight optimization by using includes.

arr2.filter(x => !arr1.includes(x))

Keep in mind this can become a slow operation for large arrays O(mn). You can optimize for large data sets by using a Set.

const arr1_set = new Set(arr1) // O(n) space
arr2.filter(x => !arr1_set.has(x)) // O(n) time

More info here: Computing set intersection in linear time?

djthoms
  • 3,026
  • 2
  • 31
  • 56
0

Your code is correct. You can also use include Method. Make sure to switch to ES7 to use it. Refer to below snippet -

var arr1 = [ 1, 2, 3, 4, 5 ];
var arr2  = [ 4, 5, 6 ];

var difference = arr1.filter(x => !arr2.includes(x));
console.log(difference);

/*
    Output: [ 1, 2, 3]
*/
0
  1. There is a method call Array.filter():
    arr2 = arr2.filter( function( el ) {
                  return arr1.indexOf( el ) < 0;
                  });
  1. Sample way:
    arr2= arr2.filter( function( el ) {
      return !arr1.includes( el );
    } );
  1. Using arrow functions:
    arr2= arr2.filter( ( el ) => !arr1.includes( el ) );
0

Hmm... I would have used a loop to solve this issue. Keep in mind that the filter method will actually return a new array and not make any changes to the array you are actually targeting. You're probably going to have to loop through arr2 and check each element to see if it is too in arr1 using a conditional or the includes method. If an element in arr2 in fact has a copy in arr1 then use the splice method to get rid of that element. Remember to keep track of what index you are testing so that you can pass it to the splice methods. Note: using the includes method would allow you to not use a loop in a loop. However, off the top of my head im not sure if this strategy will get you better than O^2. Hope this helps.

Tony
  • 78
  • 5