Skip to content

Commit ce1518e

Browse files
authored
Create countPairs.js
1 parent 6298843 commit ce1518e

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

countPairs.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* This also called 'Sock Merchant' or 'Count duplicates in array'
3+
*/
4+
5+
var data = [10, 20, 20, 10, 10, 30, 50, 10, 20, 50];
6+
7+
function countPairs(arr) {
8+
var counter = 0;
9+
10+
// Sort array
11+
arr.sort(function(a, b) {
12+
return a - b;
13+
});
14+
15+
for (var i = 0; i < data.length - 1; i++) {
16+
if (arr[i] === arr[i+1]) {
17+
counter++;
18+
i++;
19+
}
20+
}
21+
22+
return counter; // 3
23+
}
24+
25+
countPairs(data); // 3

0 commit comments

Comments
 (0)