Js检查pair是否存在于pair数组中

我有一个像这样的数组:

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

假设我有两个数字:34,我如何检查这两个数字中是否有一对(无论数组中存在它的顺序?

回答

您可以使用Array#findIndex来获取index对的 或者-1如果未找到:

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


以上是Js检查pair是否存在于pair数组中的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>