在 JavaScript 中从数组中查找匹配对

javascriptweb developmentfront end technology更新于 2024/6/20 22:13:00

我们需要编写一个 JavaScript 函数,该函数接受一个可能包含一些重复值的整数数组。我们的函数应该找出我们可以从数组中提取的相同整数对的数量。

例如 −

如果输入数组是 −

const arr = [1, 5, 2, 1, 6, 2, 2, 9];

那么输出应该是 −

const output = 2;

因为所需的对是 1、1 和 2、2

示例

其代码为 −

const arr = [1, 5, 2, 1, 6, 2, 2, 9];
const countPairs = (arr = []) => {
   const { length } = arr;
   let count = 0;
   // 进行浅拷贝,使原始数组保持不变
   const copy = arr.slice();
   copy.sort((a, b) => a - b);
   for(let i = 0; i < length; i++){
      if(copy[i] === copy[i + 1]){
         i++;
         count++;
      };
   };
   return count;
};
console.log(countPairs(arr));

输出

控制台中的输出将是 −

2

相关文章