Passing objects into the array#indexOf
method might not give the results you expect
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
Hopefully, someone else can confirm this.
Sounds like the perfect use for array.prototype.some
function hasCoordinates(array, coords) {
return array.some(function(element, coords) {
return Array.isArray(element) && String(array[element]) == String(coords);
});
}
hasCoordinates([1,3,[4,6]], [4,6])
=> should return true
We can use the isArray
method to determine if an object is array.
It should be noted that the some
function is only available in ie9 and up
To find the exact coordinates, you can not compare arrays for equality, as they are treated as different objects.
Ex.
[0,0] == [0,0]
=> false
We need to perform type conversion first
String[0,0] == String[0,0]
=> true
This is because, now the arrays are being evaluated as strings.