To shuffle an array in random order in JavaScript, you can use the sort()
function with Math.random()
or use the map()
& sort()
function. Let’s explore both approaches here.
Method 1: Using sort() and Math.random():
let arr = [1, 2, 3, 4, 5];
arr.sort(() => Math.random() - 0.5);
console.log(arr);
The above sort()
method sorts the array using a custom compare function. The compare function returns a random value between -0.5 and 0.5. This random value makes the sort() function randomly reorder the elements of the array. In this way, the array is shuffled into a random order each time it’s run.
Method 2: Using map() & sort():
let arr = [1, 2, 3, 4, 5];
let shuffled = arr
.map(value => ({ value, sort: Math.random() }))
.sort((a, b) => a.sort - b.sort)
.map(({ value }) => value);
console.log(shuffled);
Firstly, map() converts each element of the array into an object with two properties: value (the original element) and sort (a random number generated by Math.random()). hen Sorts these objects by their sort property, which randomly reorders the array based on the generated random values.
Similar Reads
- JavaScript – Sum of Digits of a NumberIn this article, we will learn how to find the sum of digits of a given number. The sum of digits can be obtained by… Read more: JavaScript – Sum of Digits of a Number
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator + reverse(). Using… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays. The problem Write… Read more: JavaScript – Find the Intersection of Two Arrays