-1

I'm trying to remove an object from an array if the object exists already in the array. I know how to remove the object but I'm using the includes() method to find out if the object exists. I can't seem to get this working properly. Here's some code:

const sampleRange = [{from: 500, to: 600}, {from: 700, to: 800}]

const objectFromRange = sampleRange[0]

const objectRange = {from: 500, to: 600}

sampleRange.includes(objectFromRange) => true

sampleRange.includes(objectRange) => false

So why does one sampleRange.includes come out to true rather the other one comes out as false? They're the same object.

Dres
  • 1,449
  • 3
  • 18
  • 35

2 Answers2

5

It is because object variables are references to a place in memory. This is the reason that objectFromRange works but objectRange doesnt. objectFromRangereferences a place in memory that is inside the array while objectRange does not. To do what you want to do use Array.some()

sampleRange.some((range)=>range.from == 500 && range.to == 600)

KolCrooks
  • 514
  • 1
  • 5
  • 12
  • 1
    "It is because object variables are references to a place in memory." This is also true in other languages, but Python in particular, implements equality comparison by the contents rather than just its address. So the other half of the answer is to explain how equality comparison works in JavaScript. – Code-Apprentice Aug 23 '19 at 17:16
1

const objectRange = {from: 500, to: 600} at this line you have created new instance of object, it is not the same object as it is in array

Dominik Matis
  • 2,086
  • 10
  • 15