A previous answer said:
You cannot use indexOf to do complicated arrays (unless you serialize it making everything each coordinate into strings)...
Here's how you'd do just that. If you have an extremely large data set, I'd recommend against this technique, as it relies on a duplicate of your 2D array. But for reasonable sets, it's simple.
Use a consistent method for flattening array elements, such as:
// Flatten array into a string, separating elements with a "unique" separator.
function stringle( arr ) {
return arr.join(' |-| ');
}
This is overkill for your example, where sub-arrays contain integers, but it accounts for more complex data types. (If we used a comma, the default, it would be indiscernible from a string element that contained a comma, for example.)
Then the target array can be flattened into an array of strings:
// Transmogrify arr into a String[], usable with indexOf()
var arrSearch = arr.map(function(row) { return stringle(row); });
Then you can use Array.indexOf()
(or other array methods) to check for the presence or location of matches.
if (arrSearch.indexOf( stringle(newArray) ) === -1) ...
This snippet contains a demo of this, with multiple data types.
// Example starting array
var arr = [[2,3],[5,8],[1,1],[0,9],[5,7]];
// Flatten array into a string, separating elements with a "unique" separator.
function stringle( arr ) {
return arr.join(' |-| ');
}
snippet.log("arr: "+JSON.stringify(arr));
// Transmogrify arr into a String[], usable with indexOf()
var arrSearch = arr.map(function(row) { return stringle(row); });
snippet.log("arrSearch: "+JSON.stringify(arrSearch));
var tests = [[0, 9],[1, 2],["pig","cow"],[0,9,"unicorn"],["pig","cow"]];
for (var test in tests) {
var str = stringle(tests[test]);
if (arrSearch.indexOf(str) === -1) {
arr.push(tests[test]);
arrSearch.push(str);
snippet.log("Added "+JSON.stringify(tests[test]));
}
else {
snippet.log("Already had "+JSON.stringify(tests[test]));
}
}
snippet.log("Result: "+JSON.stringify(arr));
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>