ANY HELP WITH JAVASCRIPT includes() function
const formA = [
{id:37,name:'New',another:'things'},
{id:31,name:'Old',another:'things'},
{id:3,name:'Oldest',another:'things'}
];
const formB = [
{id:37,name:'New',another:'things'},
{id:31,name:'Old',another:'things'},
];
const difference = formA.filter(x => !formB.includes(x.name))
console.log(difference);
would someone kindly explain to me how includes() method works?
i was expecting____ [{id:3,name:'Oldest',another:'things'}] as output
but instead getting.
//__________output
[
{ id: 37, name: 'New', another: 'things' },
{ id: 31, name: 'Old', another: 'things' },
{ id: 3, name: 'Oldest', another: 'things' }
]
Top comments (8)
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.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.i have to look into this approach, thank you very much for the response
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 usingformA.filter
. Like this.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 :)
Array.prototype.includes()
Given that your arrays itemize objects, those arrays contain references to objects, not the actual objects.
So
includes()
can't help here because it can only find one-and-the-same object (because its reference is the same) but it cannot find objects that look the same.I believe what you are looking for is Array.prototype.some().
because i was looking at this kind of approach with includes() to get the Difference between two arrays
const arrA = ['john','matha','lisa','adam']; const arrB = ['tom','andrew','lisa','adam'];
but this seems like it does not work with objects
Otherwise thank very much for your take, helps a lot lot...going to look into the approaches
JavaScript data types and data structures
Strings are a primitive type.
Objects are a structural type.
So with objects you simply have to "dig deeper" until you can compare the primitive types (referenced by the object) that matter to you.
Array.prototype.every()
thank you peerreynders, i like this approach, quiet understandable too, thanks alot for the efforts i am more than ever energised :)