How do I match pairs in a 2 dimensional array in JavaScript?

Viewed 804

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]?

3 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.

Use 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:

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.

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");

Related