How can I return only the number of matching pair values in array?
Here is another approach using a Set
:
function pairNumbers(arr) {
let count = 0;
const set = new Set();
for (let i = 0; i < arr.length; i++) {
if (set.delete(arr[i])) {
count++;
} else {
set.add(arr[i])
}
}
return count;
}
console.log(pairNumbers([10, 10, 10, 10, 20, 20, 20, 30, 50])) // 3
I'd reduce into an object, counting up the number of occurrences of each number. Then reduce again on the Object.values
of the object to count up the number of pairs, adding Math.floor(count / 2)
to the accumulator on each iteration:
function pairNumber(arr) {
const itemCounts = arr.reduce((a, item) => {
a[item] = (a[item] || 0) + 1;
return a;
}, {});
return Object.values(itemCounts)
.reduce((pairsSoFar, count) => pairsSoFar + Math.floor(count / 2), 0);
}
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))
Probably better to avoid .sort
if possible - that increases the computational complexity from O(n)
(minimum) to O(n log n)
.