0
    {
    "identityA": {
      "_id": "5e98baf27457da339b219eb8",
      "altitude": 0,
      "startTime": "2020-04-16T20:07:00.000Z",
      "endTime": "2020-04-16T20:07:00.000Z",
      "lat": 30.66702,
      "lng": 73.12998,
      "personId": "5e95dfc46cbdd81757e47da2"
    },
    "identityB": {
      "_id": "5e98baf47457da339b219eba",
      "altitude": 0,
      "startTime": "2020-04-16T20:07:00.000Z",
      "endTime": "2020-04-16T20:07:00.000Z",
      "lat": 30.66869,
      "lng": 73.13591,
      "personId": "5e97682d517976252cdab2d1"
    },
    "dist": 0.3709439708757079,
    "id": "5e98bbb77457da339b219ed6",
    "createdAt": "2020-04-16T20:10:31.314Z",
    "updatedAt": "2020-04-16T20:10:31.314Z"
  }

This is an example object of my array , would i be able to detect if i already have this object in the array using array.includes.this is my check.my goal is to not push duplicate elements

if (!finalInteractions.includes(element1)) {
   finalInteractions.push(element1);
                                           }

1 Answers1

1

Array.prototype.includes essentially compares the same way a === operator does. So for objects, it compares by reference, not by value.

That's why invoking includes with a reference will work, while invoking includes with an object that has the same property values, but is not a reference, will not work:

const arr = [
  {
    name: 'object1'
  },
  {
    name: 'object2'
  }
];

console.log(arr.includes(arr[0])); // --> true
console.log(arr.includes({name: 'object1'})); // --> false
fjc
  • 5,590
  • 17
  • 36