0

I have an array which is called ids_to_remove. When I type it in browser inspect, I get the following result:

ids_to_remove
(2) ['1', '2']

When I type in the same array I get:

['1','2']
(2) ['1', '2']

When I compare the elements I get:

ids_to_remove[0]==='1'
true
ids_to_remove[1]==='2'
true

also

typeof(ids_to_remove[0])
'string'

But when I compare the arrays:

ids_to_remove===['1','2']
false

Does anyone have any idea why these two arrays are not equal?

Neg K
  • 17
  • 7

1 Answers1

1

Javascript arrays are objects and you can't simply use the equality operator == to understand if the content of those objects is the same. The equality operator will only test if two objects are actually exactly the same instance (e.g. myObjVariable==myObjVariable, works for null and undefined too).

you can simply use this function:

function arrayEquals(a, b) {
    return Array.isArray(a) &&
        Array.isArray(b) &&
        a.length === b.length &&
        a.every((val, index) => val === b[index]);
}

This function only works for simple non primitive type arrays.

Talha Fayyaz
  • 481
  • 2
  • 9
  • Thank you! Actually the reason I compared arrays was I was using ids_to_remove as input for another function and it was not working. When I was simply writing ['1','2'] -manually- in input, it would work so I was trying to understand what is different. – Neg K Aug 15 '22 at 19:51