In TypeScript, you can use the same Fisher-Yates shuffle algorithm as in JavaScript.
In this example,
intArray
containing integers.shuffleArray
that applies the Fisher-Yates shuffle algorithm to intArray
.function shuffleArray<T>(array: T[]): T[] {
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: number[] = [1, 2, 3, 4, 5];
const shuffledArray = shuffleArray(intArray);
console.log('Shuffled Array:', shuffledArray);
Shuffled Array: [ 5, 2, 1, 4, 3 ]
In this example,
strArray
containing strings.shuffleArray
that applies the Fisher-Yates shuffle algorithm to strArray
.function shuffleArray<T>(array: T[]): T[] {
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: string[] = ['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 TypeScript language with well detailed examples.