DEV Community

Karan
Karan

Posted on • Edited on

4 1

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!

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay