-3

This is what I have

function array_diff_very_fast(a, b) {
  a = a.filter( el => !b.includes( el ) );
  return a;
}
var temp = array_diff_very_fast([1,2,2,2,2,4,5,6], [1,2,6]);
console.log(temp);

and I want it to return [4,5].

I am working in code wars and the function works but it is not efficient enough.

Ali Esmailpor
  • 1,209
  • 3
  • 11
  • 22
  • You mean "which are NOT in list b" – mplungjan Mar 24 '21 at 09:08
  • I am removing the values which are present in both lists and returning the left over values, but I can see the confusion. In your case i am removing the values in list b which are not present in list a and returning those values to a new list as the output. – LucifersFruitbowl Mar 24 '21 at 09:21

1 Answers1

1

You could take an approach with O(1) for searching the element in a data set, like a Set or an object.

Then omit using a variable just for storing a return value.

function array_diff_very_fast(a, b) {
    const bb = new Set(b);
    return a.filter(el => !bb.has(el));
}

console.log(array_diff_very_fast([1, 2, 2, 2, 2, 4, 5, 6], [1, 2, 6]));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392