When working with arrays of coordinates, viewed as arrays of length 2, it becomes necessary to verify if a certain coordinate is included in that array. However, JavaScript doesn't offer a straightforward way to do this (even when using the ES2016 method Array.includes or the older Array.indexOf, you'll encounter the same issue):
const a = [[1,2],[5,6]];
const find = a.includes([5,6]);
console.log(find);
This code snippet returns false. This has always been a point of confusion for me. Could someone please explain why it returns false? To workaround this limitation, I typically create a helper function:
function hasElement(arr,el) {
return arr.some(x => x[0] === el[0] && x[1] === el[1])
}
The condition inside can also be replaced by x.toString() === el.toString()
. Utilizing this approach, hasElement(a,[5,6])
will indeed return true.
Is there a more elegant solution for checking inclusion, preferably without resorting to writing additional helper functions?