DEV Community

Discussion on: Help with includes() in js

Collapse
 
vonheikemen profile image
Heiker • Edited

Let's just say that Array.includes is making a "shallow comparison". What is happening is that you're comparing an object against a string. Imagine something like this.

'Oldest' === ({ id:3, name:'Oldest', another:'things' })
Enter fullscreen mode Exit fullscreen mode

If you try that it would return false.

Array.includes doesn't try to find the string inside the object it, just compares the whole item in the array against your argument.

If I were to try implement Array.includes as a function it would be like this.

function includes(array, search) {
   for(const item of array) {
      if(item === search) {
         return true;
      }
   }

   return false;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
magimart profile image
Magima Felix O

i have to look into this approach, thank you very much for the response

Collapse
 
vonheikemen profile image
Heiker

Actually I was just trying to explain how Array.includes works.

What would solve your problem is to transform formB into an array of names before using formA.filter. Like this.

const formBNames = formB.map((x) => x.name);

const difference = formA.filter((x) => !formBNames.includes(x.name));
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
magimart profile image
Magima Felix O

thank your very much for your kind efforts, i tried it like you stated already but got got a desirable result. i used a set method instead and worked well.
Another contribute here also commented with reducer() that also works perfect :)