DEV Community

Karan
Karan

Posted on • Updated on

Re-assign or filter?

Hi Everyone!

A simple post here, taking a look at the comparison between what I did and what was the best solution for CodeWars Array.diff 6 Kyu problem.

Problem

Given two arrays a and b, remove items all b items from a and return, in case they don't match return a.

What I did?

  1. Go through each item in b using a forEach loop.
  2. If you find the item in a remove it and reassign a using filter function.
  3. Goto point 1 and get next item from b.
  4. When no more items left in b, return the new a.
function array_diff_ME(a, b) {
  b.forEach(function(item, index){
      a = a.filter(x=>x===item?false:true);
  });
  return a;
}

array_diff([1,2,3,4], [4,1,3]);

So what's the problem?

It uses an extra forEach loop which is not needed, and problem can be solved just by using a single filter function.

The Better Solution

As it turns out, a single filter function on a can do the trick. It works as follows:

  1. Go through each item in a and check if the item exists in b using the indexOf function.
  2. If indexOf(item) is -1, then filter function returns a true and that value is kept in a through filter, however if indexOf(item) is not -1 then filter function returns a false and item is filtered OUT of a.
  3. Return the new a.

Here's the 'pseudo'-pseudocode!

function array_diff_PEOPLE_WHO_STUFF(a, b) {
    a.filter({if (b.indexOf(current item of a) is -1) then
           return false;
              else
           return true;
    });
return a;
}

Hope you liked this, just like I liked documenting another sub-optimal way of getting stuff done :), TTYL!

Top comments (0)