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]))