svoruganti
svoruganti

Reputation: 672

Js check if pair exists in array of pairs

I have an array like so:

const arr = [[1, 2], [3, 4], [5, 7]]

Say I have two numbers: 3 and 4, how do I check if a pair of those two numbers (regardless of it's order exists in the array?

Upvotes: 3

Views: 1432

Answers (2)

Ruban Prakash
Ruban Prakash

Reputation: 83

EDIT: The following method only works when the two numbers are unique, i.e when a !== b

This can be done with a for loop and the built in Array.includes(), which returns a Boolean if the specified value is present in the array

const arr = [[1, 2], [3, 4], [5, 7], [3, 4]];

function hasPair(array, a, b) {
    let pairStatus = false;
    for(let pair of arr) {
        if (pair.includes(a) && pair.includes(b)) {
            pairStatus = true;
        }
    }
    return pairStatus;
}

console.log(hasPair(arr, 1, 4)); // false
console.log(hasPair(arr, 3, 4)); // true

If you want to find how many instances of the pair exist in the array, you can just replace the pairStatus variable with a counter to increment

const arr = [[1, 2], [3, 4], [5, 7], [3, 4]];

function instancesOfPair(array, a, b) {
    let instances = 0;
    for(let pair of arr) {
        if (pair.includes(a) && pair.includes(b)) {
            instances++;
        }
    }
    return instances;
}

console.log(instancesOfPair(arr, 3, 4)); // 2

Upvotes: 3

Majed Badawi
Majed Badawi

Reputation: 28414

You can use Array#findIndex to get the index of the pair or -1 if not found:

const arr = [[1, 2], [3, 4], [5, 7]];

const searchForPairInList = (a, b) =>
  arr.findIndex(([first, second]) => 
    (first === a && second === b) || (first === b && second === a)
  );

console.log( '3, 4:', searchForPairInList(3, 4) );
console.log( '7, 5:', searchForPairInList(7, 5) );
console.log( '3, 3:', searchForPairInList(3, 3) );

Upvotes: 6

Related Questions