Say I found a box of loose shoes (all the same kind) at a garage sale, and I've created an array with each individual shoe listed by shoe size.
I want to display the number of paired values of shoe sizes in the array. For example, I have this array:
[10,10,10,10,20,20,20,30,50]
I would like to display 3
because we have 3 pairs of numbers:
10,10
10,10
20,20
And 3 remaining values that don't have a matching pair-value (20,30,50
).
How can I do this?
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]))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With