javascript
Methods to shuffle an array using javascript
In this post, we are going to explain different methods that can be used to shuffle an array in javascript. We will be randomizing the array and putting the array elements in different orders each time the function is executed.
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]
Example 2: Use Array.sort() and Math.random() to shuffle array
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]
Was this helpful?
Similar Posts
- Methods to check empty array using javascript
- Efficiently Remove the Last Element from an Array in JavaScript [6 Methods Explained]
- Check if string includes a substring Javascript (Multiple Methods)
- Sort array using Array.sort() in javascript
- Break an array into fixed length array groups using lodash in Javascript
- Convert a string to array using Array.from() in javascript
- Javascript Code for Sorting array and finding Largest No. in Array