DEV Community

Discussion on: Help with includes() in js

Collapse
 
magimart profile image
Magima Felix O

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'];

                    const myDiff = arrA.filter(name => !arrB.includes(name))
                    console.log(myDiff)
Enter fullscreen mode Exit fullscreen mode

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

Collapse
 
peerreynders profile image
peerreynders • Edited
const arrA = ['john','matha','lisa','adam']; 
const arrB = ['tom','andrew','lisa','adam'];

console.log(arrA.filter(name => !arrB.includes(name))); // ["john", "matha"]
console.log(arrA.filter(name => !arrB.some(other => other === name))); // ["john", "matha"]
console.log(arrA.filter(name => arrB.every(other => other !== name))); // ["john", "matha"]
Enter fullscreen mode Exit fullscreen mode

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.

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' },
];

console.log(
  formA.filter((itemA) => formB.every((itemB) => itemB.name !== itemA.name))
); // [ {id: 3, name: "Oldest", another: "things" } ]

function differenceByName(itemsA, itemsB) {
  const keepNotInB = (itemA) => {
    const isNameDifferent = (itemB) => itemB.name !== itemA.name;
    return itemsB.every(isNameDifferent);
  };
  return itemsA.filter(keepNotInB);
}

console.log(differenceByName(formA, formB)); // [ {id: 3, name: "Oldest", another: "things" } ]
Enter fullscreen mode Exit fullscreen mode

Array.prototype.every()

Thread Thread
 
magimart profile image
Magima Felix O

thank you peerreynders, i like this approach, quiet understandable too, thanks alot for the efforts i am more than ever energised :)