function random_array(arr) {
let idx = arr.length, random_num;
while (idx != 0) {
random_num = Math.floor(Math.random() * idx);
idx--;
[arr[idx], arr[random_num]] = [
arr[random_num], arr[idx]];
}
return arr;
}
// Test the code
const result = random_array([10, 20, 30, 40, 50]);
console.log(result);
Output
[50,10,20,30,40]
Here we are using javascript functions Array.sort() and Math.random() to randomize an array.
Code Example
const arr_shuffle = (arr) => arr.sort(() => Math.random() - 0.5);
const my_array = [10, 20, 30, 40, 50, 60, 70];
console.log(arr_shuffle(my_array));
Output
[50,30,60,20,10,40,70]
0 Comments