首页 > 解决方案 > Best way to check if some coordinate is contained in an array (JavaScript)

问题描述

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?

标签: javascriptarrays

解决方案


您可以使用JSON.stringify方法将 javascript 对象或值转换为 JSON 字符串,然后对要搜索的数组执行相同操作,并检查主数组是否包含您要查找的数组。

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


推荐阅读