最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Js check if pair exists in array of pairs - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Apr 21, 2021 at 17:46 AbsoluteBeginner 2,2633 gold badges14 silver badges24 bronze badges asked Apr 21, 2021 at 16:21 svorugantisvoruganti 6821 gold badge7 silver badges30 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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

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

发布评论

评论列表(0)

  1. 暂无评论