By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
Responding to and Tracking Key Presses
How to Work With Responding to and Tracking Key Presses
JavaScript
Passing a JavaScript Value Between HTML Pages
Passing a JavaScript Value Between HTML Pages
JavaScript
Compare Objects in an Array
JavaScript Problem: Compare Objects in an Array
JavaScript
Switching Name Order Using Capturing Groups in Regular Expressions
Switching Name Order Using Capturing Groups in Regular Expressions
JavaScript
Shuffling an Array
JavaScript Problem: How to Perform Shuffling an Array
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > JavaScript Problem: How to Perform Shuffling an Array
JavaScript

JavaScript Problem: How to Perform Shuffling an Array

Admin
Last updated: 2023/01/27 at 5:54 AM
Admin
Share
5 Min Read
Shuffling an Array

In this article, we are going to see about shuffling an array in JavaScript. Shuffling can be a very useful feature while creating some applications like quiz, scramble games etc. or might be useful in many ways. So we will make this thing happens with some simple and basic way. We will take an array of element or numbers, and we will apply some logic on them to shuffle in random order. So let’s see how we can do it.

Contents
Shuffling an Array: Classical WayShuffling an Array: Alternative WayYou may also like:

Shuffling an Array: Classical Way

Okay, so we can perform this shuffling task using Math.random() method, which returns a random number between 0 and 1. So, as you can see in the below code, we have created an array of some random elements. Now we have created a function which takes an array as parameter, then we added a for loop in this function. We will run this loop from the length of the array till i>0 condition, and we are just decrementing the value of i.

In this loop, we are calling Math.random() method, which simply returns a random value from 0 to 1, and we will multiply this value with 1 incremented value of i. For example, if Math.random() returns 0.45543 then we will multiply with i+1 which is let say is 6, then we will get 2.73158. Now we need only integer number since array’s indexes are in integer, for that we have to apply Math.floor() method which will removes the decimal part and returns integer (here 2).

After getting a random position, we need to store that value of the same index into temp, and we will assign array of new position in that array index. And finally, we will assign the value of temp into the array of new position index.

It seems pretty awkward to understand, so let’s see an example for that, let’s assume we are on first rotation of loop, here i = 5 and let’s say we got newpos =3. So now temp will be empty by default, so with this temp = arry[5] (since i=5) line will assign the value of arry[5] into the temp (here arr[5] = “fish”). And arry[5]= arr[3], so arry[5] = “dog”, finally arry[3] =temp, so arry[3]= “fish”.


        let arr = ["apple","banana","cat","dog","egg","fish"];

        let newArr = function(arry){
            let temp,
                newpos;

            for(let i= arry.length - 1; i>0; i--){
                newpos = Math.floor(Math.random() * (i+1));
                temp = arry[i];
                arry[i] = arry[newpos];
                arry[newpos] = temp;
            
            }
            return arry;
        }
        console.log(arr);
        
        let arr1 = newArr(arr);
        
        console.log(arr1);
Shuffling an Array

Shuffling an Array: Alternative Way

It is the possibility that we can perform this task with some other ways, but here is another way to do this same thing which makes code a little bit smaller than before. As you can see below, we have made another simple logic which is way smaller than above one using just sort() method. So here we are returning Math.random() - 0.5 in sort method. This method also known as comparison method where we are deciding swapping of value based on nature of random number.

For example, we have called this method for the first time, then callback function will be run here Math.random returns a value between -0.5 to 4.9999. So if this returns a negative value, then the first two will not be swapped. And if it is positive then both values will be swapped (here swapping will be done among the first two value since it is first iteration).

Let’s say we got -0.43 at first iteration, then apple and banana won’t be swapped. And let’s say at second iteration we got something like 0.2 then banana and cat will be swapped (here banana won’t be always in the pair with cat, it depends on previous swapping condition).


        let arr = ["apple","banana","cat","dog","egg","fish"];

        let newArr = function(arry){
            return arry.sort( ()=>Math.random()-0.5 );
            
            }
            
        
        console.log(arr);
        
        let arr1 = newArr(arr);
        
        console.log(arr1);
   
Shuffling an Array

You may also like:

  • How to Define a Class With Properties and Methods in JavaScript?
  • How to Implement Class Inheritance in JavaScript?
  • How to Find Duplicate Elements in a Given Array?

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

TAGGED: javascript, Shuffling an Array, Shuffling an Array in JavaScript
Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Posted by Admin
Follow:
Rocoderes is a blog you can learn HTML, CSS, JavaScript, React Js and Python along with creative coding stuff and free source code files.
Previous Article Create a Non-duplicated Collection JavaScript Problem: Using Set to Create a Non-duplicated Collection
Next Article Switching Name Order Using Capturing Groups in Regular Expressions Switching Name Order Using Capturing Groups in Regular Expressions
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

Responding to and Tracking Key Presses

How to Work With Responding to and Tracking Key Presses

February 5, 2023
Passing a JavaScript Value Between HTML Pages

Passing a JavaScript Value Between HTML Pages

February 3, 2023
Compare Objects in an Array

JavaScript Problem: Compare Objects in an Array

January 30, 2023
Switching Name Order Using Capturing Groups in Regular Expressions

Switching Name Order Using Capturing Groups in Regular Expressions

January 29, 2023
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?