# javascript - 如何仅返回数组中配对值的数量?

## (3)

`````` function pairNumber(arr) {
const sorted_arr = [...arr].sort(); // disallowing array mutation
let cnt = 0;
for (let i = 0; i < sorted_arr.length; i++) {
if (sorted_arr[i + 1] === sorted_arr[i]) {
cnt++;
i = i + 1;
}

}
return cnt;
}
console.log(pairNumber([10, 10, 10, 10, 10, 20, 20, 20, 20, 30, 30, 50]))
// 5 --> 2 pairs of 10, 2 pairs of 20, 1 pair of 30
console.log(pairNumbers([10, 10, 10, 10, 20, 20, 20, 30, 50]))
// 3 --> 2 pairs of 10 one pair of 20``````

``[10,10,10,10,20,20,20,30,50]``

``````function pairNumber(arr) {
var sorted_arr = arr.sort();
var i;
var results = [];
for (i = 0; i < sorted_arr.length; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}

}
return results.length;
}
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))``````

``````function pairNumber(arr) {
const itemCounts = arr.reduce((a, item) => {
a[item] = (a[item] || 0) + 1;
return a;
}, {});
return Object.values(itemCounts)
}
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))``````

``````function pairNumbers(arr) {
const sorted_arr = arr.sort();
const results = [];
for (let i = 0; i < sorted_arr.length; i++) {
if (sorted_arr[i] == sorted_arr[i + 1]) {
results.push(sorted_arr[i]);
i = i + 1;
}

}
return results.length;
}
console.log(pairNumbers([10, 10, 10, 10, 20, 20, 20, 30, 50])) // 3``````