Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Is there a way to find this array without relying on numberStore[4]?

like image 537
zadubz Avatar asked Aug 25 '26 00:08

zadubz


1 Answers

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.

like image 195
Phil Avatar answered Aug 27 '26 14:08

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!