We randomize elements in a JavaScript array using various approaches. Here, I have used Fisher-Yates Sorting Algorithm in this swap each element in the array with the randomly selected element from the remaining un-shuffled portion of the array.
function shuffleArr(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
const originalArr = [11, 22, 33, 44, 55];
const shuffledArr = shuffleArr(originalArr);
console.log(shuffledArr);