If you want to search for a specific coordinate in a 2D array, using indexOf is not the most efficient option unless you serialize the array first. Instead, it's recommended to use a for loop or while loop to iterate through the array and compare each coordinate individually.
var arr = [[2,3],[5,8],[1,1],[0,9],[5,7]];
var coor1 = [0, 9];
var coor2 = [1, 2];
function isItemInArray(array, item) {
for (var i = 0; i < array.length; i++) {
if (array[i][0] == item[0] && array[i][1] == item[1]) {
return true; // Found it
}
}
return false; // Not found
}
// Test coor1
console.log("Is it in there? [0, 9]", isItemInArray(arr, coor1)); // True
// Test coor2
console.log("Is it in there? [1, 2]", isItemInArray(arr, coor2)); // False
// Then
if (!isItemInArray(arr, [x, y])) {
arr.push([x, y]);
}
This method loops through all values in the array. For better performance, consider sorting the original array by the first index and using binary search for faster lookup.
Another approach is to create buckets based on the first coordinate of each item in the array using an object like a hashtable, and then further bucket the second values within those buckets to improve search efficiency. More information on this technique can be found here: http://en.wikipedia.org/wiki/Bucket_sort.
If these optimizations are unnecessary for your needs, the standard loop implementation should suffice.