25

I have an array of objects which I'm using the .includes() function. I'm searching this array with an object that is in the array (Objects are identical). However there doesn't appear to be a match. I have replicated the problem in this fiddle. The code is also below. So what is the correct way to check if an array contains am object?

let list1 = [{
    name: "object1"
  },
  {
    name: "object2"
  },
  {
    name: "object3"
  },
  {
    name: "object4"
  }
]


if (list1.includes({
    name: "object1"
  })) {
  document.write('contains')
} else {
  document.write('doesnt')
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Harvey Lewis
  • 253
  • 1
  • 3
  • 4
  • 3
    When you're saying .include({ ... }) you're not asking if the array includes an object with these values, you're asking if the array contains an object that has the same reference in memory as the object literal you just instanced by passing { ... } as a value - answer is no, it does not :) You should use a method that lets you pass a callback to check for equality of interesting values (ie: .find) – Fabio Lolli May 16 '18 at 12:45
  • 1
    More specifically, when looking for a match, `Array.include` compares the target and element with `Object.is()`. That's mostly the same as `===`, which means two object references are considered equal only if they point to the same place in memory. (The differences from `===` relate to special floating-point values, which `===` treats precisely according to the IEEE 754 spec, while `Object.is` violates the spec to provide what is arguably less surprising behavior: `Object.is(NaN,NaN)` is true, while `Object.is(+0,-0)` is false.) – Mark Reed May 16 '18 at 13:00

2 Answers2

26

You can't compare objects directly, but using this method , you can compare them with JSON.stringify.

let list1 = [{
    name: "object1"
  },
  {
    name: "object2"
  },
  {
    name: "object3"
  },
  {
    name: "object4"
  }
]

var contains = list1.some(elem =>{
  return JSON.stringify({name: "object1"}) === JSON.stringify(elem);
});
if (contains) {
  document.write('contains')
} else {
  document.write('doesnt')
}
Renzo Calla
  • 7,486
  • 2
  • 22
  • 37
  • It doesn't seem like the return statement is needed. Something like this: `var contains = arr.some(elem => JSON.stringify(obj) === JSON.stringify(elem));` works just as well and is shorter. – TheLastAirbender Apr 01 '22 at 09:33
8

You can try following

let list1 = [{name:"object1"},{name:"object2"},{name:"object3"},{name:"object4"}]


if (list1.some(({name}) => name === "object1")) {
  document.write('contains')
} else {
  document.write('doesnt')
}
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59