Sling Academy
Home/JavaScript/3 Ways to Shuffle an Array in JavaScript

3 Ways to Shuffle an Array in JavaScript

Last updated: February 19, 2023

This practical article walks you through 3 different approaches to shuffling a given array in Javascript.

Using Sort() Function

You can shuffle an array by generating random numbers and comparing them in the sort() function.

Example:

const arr = ['dog', 'cat', 'dragon','slingacademy.com', 'banana'];

const shuffledArr = arr.sort(() => Math.random() - 0.5);
console.log(shuffledArr);

The Math.random() function generates a random number between 0 and 1 (inclusive of 0 but exclusive of 1). When we subtract 0.5 from this random number, we get a new random number that can be positive or negative, with an equal probability of being either.

Output:

[ 'cat', 'dog', 'slingacademy.com', 'banana', 'dragon' ]

The output will likely change each time you execute the code

Using For Loop

In this approach, we will iterate over the array in reverse order and swap each element with a randomly selected element from the range of unshuffled elements.

Example:

const arr = ['dog', 'cat', 'dragon', 'slingacademy.com', 'banana'];

// define a function that can be reused
const shuffleArray = (array) => {
  // create a copy of the array so that the original array is not mutated
  const newArray = [...array];
  for (let i = newArray.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
  }
  return newArray;
};

// use the function
const shuffledArray = shuffleArray(arr);
console.log(shuffledArray);

Output:

[ 'slingacademy.com', 'cat', 'banana', 'dragon', 'dog' ]

Using Lodash

Lodash is a super popular multi-purpose Javascript open-source library. You can add it to your project by running:

npm i lodash

And use the shuffle() function of lodash to get the job done quickly:

import _ from 'lodash'

const arr = [1, 2, 3, 4, 5]
const shuffleArr = _.shuffle(arr)

console.log(shuffleArr)

Output:

[ 5, 1, 2, 3, 4 ]

Next Article: How to effectively use the filter() method in Javascript

Previous Article: How to Remove Elements from an Array in JavaScript

Series: Working with Arrays in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration