[英]How do I match pairs in a 2 dimensional array in JavaScript?
I have an array with pairs of numbers and need to find matching pairs within the array 我有一对数组,需要在数组中找到匹配的对
numberStore = [ [0,0],[1,1],[1,2],[1,3],[1,4],[1,5]... ]
I want to be able to find 1,4
. 我希望能找到
1,4
。 Is there a way to find this array without relying on numberStore[4]
? 有没有办法在不依赖
numberStore[4]
情况下找到这个数组?
Since you need to perform this search frequently, I would build a hashed set to avoid mapping and searching over and over. 由于您需要经常执行此搜索,我将构建一个散列集以避免一遍又一遍地进行映射和搜索。 For example
例如
const numberStore = [ [0,0],[1,1],[1,2],[1,3],[1,4],[1,5] ] const hashedSet = new Set(numberStore.map(pair => pair.toString())) // looks like ["0,0", "1,1", "1,2", "1,3", etc] console.log([...hashedSet]) const search = (find) => { return hashedSet.has(find.toString()) } console.info('Find [1,4]', search([1,4])) console.info('Find [4,1]', search([4,1]))
I've used Array.prototype.toString()
as the hashing function but you could substitute anything there that creates a unique and comparable entity for each pair. 我已经使用
Array.prototype.toString()
作为散列函数,但是您可以替换那些为每对创建唯一且可比较的实体的任何东西。
Use Array.prototype.find()
: 使用
Array.prototype.find()
:
var numberStore = [ [0, 0], [1, 1], [1, 2], [1, 3], [1, 4], [1, 5] ]; var oneFour = numberStore.find(function([a, b]) { return a == 1 && b == 4; }); console.log(oneFour);
Or if you prefer ES6 arrow syntax : 或者如果您更喜欢ES6箭头语法 :
var numberStore = [ [0, 0], [1, 1], [1, 2], [1, 3], [1, 4], [1, 5] ]; var oneFour = numberStore.find(([a, b]) => a == 1 && b == 4); console.log(oneFour);
Another alternative is using the method some() to test elements for a condition. 另一种方法是使用方法some()来测试条件的元素。
var numberStore = [ [0,0], [1,1], [1,2], [1,3], [1,4], [1,5] ]; var exists = numberStore.some(([a, b]) => a === 1 && b === 4); console.log(exists ? "Pair [1,4] exists" : "Pair [1,4] don't exists");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.