Articles by FavTutor
  • AI News
  • Data Structures
  • Web Developement
  • AI Code GeneratorNEW
  • Student Help
  • Main Website
No Result
View All Result
FavTutor
  • AI News
  • Data Structures
  • Web Developement
  • AI Code GeneratorNEW
  • Student Help
  • Main Website
No Result
View All Result
Articles by FavTutor
No Result
View All Result
Home Web Developement

How to Shuffle an Array in JavaScript? (with code)

Komal Bhatia by Komal Bhatia
January 31, 2024
Reading Time: 5 mins read
How to Shuffle an Array in JavaScript
Follow us on Google News   Subscribe to our newsletter

Shuffling is a common operation in programming that is used to introduce randomness. In this article, we will look into some easy methods to shuffle an array in JavaScript.

4 Methods to Shuffle an Array in JavaScript

Arrays are linear data structures that store homogenous data, i.e. same type of data. An array can contain all integers, all characters, or all strings as the elements.

Shuffling an array is the process of reordering the elements within the array randomly. After shuffling, the elements are rearranged in a random order that is different from the original order of the array. There are various reasons why we need to shuffle arrays in programming:

  • Randomization can help in designing games, statistical sampling, as well as in cryptography.
  • Sometimes in algorithms, having a predictable order of elements results in biases. Shuffling helps to remove those biases.
  • It can be useful during testing and debugging to test that the program gives correct output under different permutations of input data.

let’s now look into methods to shuffle an array. Let us get started!

1) Fisher-Yates Algorithm

Fisher-Yates Algorithm is a popular algorithm for shuffling an array in JavaScript. It is also called Knuth Shuffle. In it, we iterate over the array in reverse order and swap each element with a random one from the remaining unshuffled portion of the array. 

Check the example below:

//declaring an array
let arr=[1,2,3,4,5];

//shuffling an array
for(let i=arr.length-1;i>0;i--){
    const u=Math.floor(Math.random()*(i+1));
    //swapping two elements
    [arr[i],arr[u]]=[arr[u],arr[i]];
}

//printing the shuffled array
for(let i=0;i<arr.length;i++){
    console.log(arr[i]);
}

Output:

3
2
4
5
1

In this example, we declared an array and used the Math.random() function to use random indices and swap them with current ones. In this way, we shuffled the array. We have obtained the desired output. 

2) Using Underscore.js Library

Underscore.js is one of the libraries of JavaScript that have built-in functions such as shuffle functions. It provides an easy way to shuffle arrays without implementing the shuffling logic.

Let us see an example using the Underscore.js library:

//importing the underscore library
const _ = require('underscore');

//declaring an array
let arr=[1,2,3,4,5];

//shuffling an array
const shuffledArr = _.shuffle(arr);

//printing the shuffled array
for(let i=0;i<arr.length;i++){
    console.log(shuffledArr[i]);
}

Output:

5
3
1
4
2

In this example, we have imported the library Underscore and used the shuffle function to shuffle or randomize the array. We have obtained the desired result.  

3) Using Lodash Library

Lodash is another one of the JS libraries that have built-in functions such as shuffle functions. It provides an easy way to shuffle arrays without implementing the shuffling logic. Note that the shuffle function of the Lodash Library uses the Fisher-Tates Algorithm. 

Let us see an example:

//importing the Lodash library
const _ = require('Lodash');

//declaring an array
let arr=[1,2,3,4,5];

//shuffling an array
const shuffledArr = _.shuffle(arr);

//printing the shuffled array
for(let i=0;i<arr.length;i++){
    console.log(shuffledArr[i]);
}

Output:

3
2
5
4
1

In this example, we have imported the library Lodash and used the shuffle function to shuffle or randomize the array. We have obtained the desired result. The array is printed in a shuffled manner.

4) Drustenfield Shuffle Algorithm

The Drustenfield Shuffle Algorithm is another algorithm for this purpose. It is an optimized version of the Fisher-Yates Algorithm.

This algorithm selects a random value for each array index and excludes the selected value from the next pick. The Drustenfield Shuffle Algorithm also works in the backward direction. It also has a time complexity of O(N). It was designed before the Fisher-Yates algorithm. 

Let us take an example.:

//declaring an array
let arr=[1,2,3,4,5];

//shuffling an array
for(let i=arr.length-1;i>0;i--){
    const u=Math.floor(Math.random()*(i+1));
    //swapping two elements
    let temp = arr[i];
    arr[i] = arr[u];
    arr[u] = temp;

}

//printing the shuffled array
for(let i=0;i<arr.length;i++){
    console.log(arr[i]);
}

Output:

5
2
3
4
1

In this algorithm, we have used the Drustenfield Algorithm to shuffle the array. This method was used before es6. We have obtained the desired result. 

Also, learn how to sort an array of objects in JavaScript using different approaches.

Conclusion

In this article, we learned how to shuffle an array in JavaScript. We can use the Fisher-Yates Algorithm, Drustenfield Algorithm, or libraries like Underscore or Lodash to shuffle an array. Try practicing different methods on different arrays and choose the suitable one according to your requirements.

ShareTweetShareSendSend
Komal Bhatia

Komal Bhatia

I am a dedicated Computer Science student with a strong track record of academic excellence. I am a highly motivated individual with a passion for providing creative and innovative solutions to complex problems. I possess skills in the domain of C++ and web development and am always eager to contribute to the field of Software Development.

RelatedPosts

Javascript Animation Libraries

Top 10 JavaScript Animation Libraries in 2025

February 19, 2025
JavaScript Interview Questions

Top 40 JavaScript Interview Questions and Answers in 2024

April 1, 2025
Best React UI Component Libraries

10 Must-Know React UI Component Libraries for Web Devs 2024

May 7, 2024
Currying in JavaScript

Currying in JavaScript Explained (with Examples)

March 15, 2024
Javascript Format Currency

Javascript Program for Format Currency

April 8, 2025

About FavTutor

FavTutor is a trusted online tutoring service to connects students with expert tutors to provide guidance on Computer Science subjects like Java, Python, C, C++, SQL, Data Science, Statistics, etc.

Categories

  • AI News, Research & Latest Updates
  • Trending
  • Data Structures
  • Web Developement
  • Data Science

Important Subjects

  • Python Assignment Help
  • C++ Help
  • R Programming Help
  • Java Homework Help
  • Programming Help

Resources

  • About Us
  • Contact Us
  • Editorial Policy
  • Privacy Policy
  • Terms and Conditions

Website listed on Ecomswap. © Copyright 2025 All Rights Reserved.

No Result
View All Result
  • AI News
  • Data Structures
  • Web Developement
  • AI Code Generator
  • Student Help
  • Main Website

Website listed on Ecomswap. © Copyright 2025 All Rights Reserved.