# JavaScript algorithms I commonly use

## Arrays:

### 1. Randomly Select X items from an array with no duplicates.

So let's say I have a row of barrels I want to randomly blow up, and they are represented in a JavaScript array. Here's how I do it:var barrels = new Array('1','2','4','5','6','7','8','9','10'); var numToSelect = 4; barrels.sort( function() { return 0.5 - Math.random() } ); // ["5", "1", "6", "4", "8", "7", "10", "2", "9"] barrels.sort( function() { return 0.5 - Math.random() } ); // ["5", "4", "8", "9", "1", "7", "6", "10", "2"] var selectedBarrels = barrels.splice(0,numToSelect); // ["1", "5", "7", "10"]

How `sort()`

normally works is that it loops through the array and compares 2 numbers at a time moving them if the anonymous function given evaluates as true; Instead we're replacing that sort function with one which will randomly return true or false. This works because Math.random() returns a value between 0.0 and 0.9999. So 0.5 - 0.6 is -0.09999, or negative, or boolean false in JavaScript. And 0.5 - 0.1 is 0.4 or positive or boolean true in JavaScript. So essentially it will randomly sort the array. Then we splice the first X elements of the newly sorted array and we are left with X randomly selected barrels.