在 JavaScript 中从数组中查找匹配对
我们需要编写一个 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;
// making a shallow copy so that the original array remains unaltered
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP