To shuffle an array in JavaScript, you can use the Fisher-Yates shuffle algorithm.
In this example,
intArray
containing integers.intArray
.function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
const intArray = [1, 2, 3, 4, 5];
const shuffledArray = shuffleArray(intArray);
console.log('Shuffled Array:', shuffledArray);
Shuffled Array: [ 3, 1, 4, 5, 2 ]
In this example,
strArray
containing strings.strArray
.function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
const strArray = ['apple', 'banana', 'cherry'];
const shuffledArray = shuffleArray(strArray);
console.log('Shuffled Array:', shuffledArray);
Shuffled Array: [ 'banana', 'cherry', 'apple' ]
In this tutorial, we learned How to Shuffle an Array in JavaScript language with well detailed examples.