Best way to check if some coordinate is contained in an array (JavaScript)

Viewed 979

When dealing with arrays of coordinates, seen as arrays of length 2, it is necessary to check if some coordinate is contained in that array. However, JavaScript cannot really do that directly (here I use that ES2016 method Array.includes, but with the more classical Array.indexOf the same issue appears):

const a = [[1,2],[5,6]];
const find = a.includes([5,6]);
console.log(find);

This returns false. This has always bothered me. Can someone explain to me why it returns false? To solve this issue, I usually define a helper function:

function hasElement(arr,el) {
     return arr.some(x => x[0] === el[0] && x[1] === el[1])
}

The inner condition here could also be replaced by x.toString() === el.toString(). Then in the example above hasElement(a,[5,6]) returns true.

Is there a more elegant way to check the inclusion, preferably without writing helper functions?

4 Answers

The reason is that in JavaScript, arrays are just objects and cannot be compared like values. Two object instances will never be equal, so even though they look identical to the eye, they are completely different objects and therefore will always be unequal. See:

console.log([5, 6] === [5, 6]) // false

The JavaScript Array class is a global object that is used in the construction of arrays; which are high-level, list-like objects.

You can use JSON.stringify method to convert the javascript object or value to a JSON string and then do the same for the array you want to search and just check if the main array includes the array you want to find.

const a = [[1,2],[5,6]], array = [5,6];
const find = JSON.stringify(a).includes(JSON.stringify(array));
console.log(find);

You can try with find and destructure to simplify.

const a = [
  [1, 2],
  [5, 6]
];

const target = [5, 6];

// Method 1
const find = a.find(x => x.every(y => target.includes(y)));

// Method 2
const [xt, yt] = target;
const find2 = a.find(([x, y]) => xt === x && yt === y);

console.log(find, find2);

Referring back to Siva K V's answer. If you want to find the index of the first occurrence in the array where this is true, just replace find with findIndex (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex)

const a = [
  [1, 2],
  [5, 6]
];

const target = [5, 6];

// Method 1
const find = a.findIndex(x => x.every(y => target.includes(y)));

// Method 2
const [xt, yt] = target;
const find2 = a.findIndex(([x, y]) => xt === x && yt === y);

console.log(find, find2);

Related