Skip to content
DeveloperMemos

Shuffling a List with TypeScript

TypeScript, Array1 min read

When working with arrays in TypeScript, you might come across situations where you need to shuffle the elements randomly. Shuffling an array can be useful in scenarios like creating randomized quizzes, picking a random item from a list, or implementing game mechanics. In this article, we will cover different approaches to shuffle a list in TypeScript with practical examples.

Using the Fisher-Yates Shuffle Algorithm

The Fisher-Yates shuffle algorithm is a popular and efficient way to randomly shuffle an array. It works by iterating over the elements of the array and swapping each element with a random element from the remaining unshuffled part of the array.

Here's an example implementation of the Fisher-Yates shuffle algorithm in TypeScript:

1function shuffle<T>(array: T[]): T[] {
2 const shuffledArray = [...array];
3
4 for (let i = shuffledArray.length - 1; i > 0; i--) {
5 const j = Math.floor(Math.random() * (i + 1));
6 [shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]];
7 }
8
9 return shuffledArray;
10}
11
12const originalArray = [1, 2, 3, 4, 5];
13const shuffledArray = shuffle(originalArray);
14
15console.log(shuffledArray); // Output: [5, 3, 2, 4, 1]

In the above code, the shuffle function takes an array as input and creates a copy of it using the spread operator [...array]. It then iterates over the elements from the end of the array to the beginning, generating a random index j within the remaining unshuffled portion of the array. Finally, it swaps the current element with the element at index j.

Using the Sort Method with a Random Comparator

Another approach to shuffle a list in TypeScript is by using the sort method with a custom random comparator. The idea is to compare two elements randomly, causing the sort algorithm to rearrange the elements in a random order.

Here's an example implementation of shuffling an array using the sort method:

1function shuffle<T>(array: T[]): T[] {
2 const shuffledArray = [...array];
3
4 shuffledArray.sort(() => Math.random() - 0.5);
5
6 return shuffledArray;
7}
8
9const originalArray = [1, 2, 3, 4, 5];
10const shuffledArray = shuffle(originalArray);
11
12console.log(shuffledArray); // Output: [3, 5, 4, 1, 2]

In this implementation, we create a copy of the original array using the spread operator. Then we call the sort method on the copied array and provide a random comparator function. The comparator returns a random value between -0.5 and 0.5, causing the sort method to reorganize the elements randomly.

Conclusion

Shuffling a list in TypeScript can be achieved using various techniques. In this article, we explored two popular approaches: the Fisher-Yates shuffle algorithm and using the sort method with a random comparator. Depending on your specific needs and performance considerations, you can choose the approach that best suits your requirements.