JavaScript Coding Challenge #2

Sock Merchant

As you can see, we can match three pairs of socks. Thus, we print 3 on a new line.
function socksForSale(socks){}
function socksForSale(socks){    socks.sort();}
function socksForSale(socks){    socks.sort(function(a, b){
return a - b;
});
}
function socksForSale(socks){    socks.sort(function(a, b){
return a - b;
});
var counter = 0; for(var i=0; i<socks.length; i++){
if(socks[i] === socks[i+1]){
counter++;
}
}
return counter;
}
function socksForSale(socks){    socks.sort(function(a, b){
return a - b;
});
var counter = 0; for(var i=0; i<socks.length; i++){
if(socks[i] === socks[i+1]){
counter++;
i++;
}
}
return counter;
}
function socksForSale(socks){    socks.sort(function(a, b){
return a - b;
});
var counter = 0; for(var i=0; i<socks.length - 1; i++){
if(socks[i] === socks[i+1]){
counter++;
i++;
}
}
return counter;
}
var socks = [1, 30, 2, 10, 8, 2, 10, 8, 4, 2, 1];
var socks2 = [10, 20, 20, 10, 10, 30, 50, 10, 20];
socksForSale(socks); // returns 4
socksForSale(socks2); // returns 3

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store