Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return 0.5 - Math.random()});
points.sort(function(a, b){return 0.5 - Math.random()});
The Fisher Yates Method
The above example, array.sort(), is not accurate, it will favor some numbers over the others.
The most popular correct method, is called the Fisher Yates shuffle, and was introduced in data science as early as 1938!
In JavaScript the method can be translated to this:
Example
const points = [40, 100, 1, 5, 25, 10];
for (let i = points.length -1; i > 0; i--) {
let j = Math.floor(Math.random() * i)
let k = points[i]
points[i] = points[j]
points[j] = k
}
for (let i = points.length -1; i > 0; i--) {
let j = Math.floor(Math.random() * i)
let k = points[i]
points[i] = points[j]
points[j] = k
}
Practice Excercise Practice now