I think it would. With real cards we shuffle the deck and then pick some cards from the top of the top of the deck. This is what you'll probably be doing with the shuffle function, thereby modelling the real world use.

With Math.Random(), you're randomly picking a card from an un-shuffled deck. The key here is randomness (which is not really random btw). So, although this isn't modelled after the real world use, the end result is the same.

I would suggest Math.Random() because it will, although not significantly, be faster than using _.shuffle's (Fisher–Yates) algorithm.

Answer from reggaemahn on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › lodash-_-shuffle-method
Lodash _.shuffle() Method - GeeksforGeeks
September 3, 2024 - Lodash _.shuffle() method creates an array of shuffled values from the given collection using a version of the Fisher-Yates shuffle algorithm.
Discussions

javascript - Shuffle multiple arrays in the same way but with Lodash - Stack Overflow
There's a few posts on stackoverflow that shuffle arrays in the way I described --this one is pretty great-- but none of them demonstrate how to shuffle two arrays using Lodash. The JavaScript methods library is known as weak, it has the sort() method but it doesn't have the shuffle() method, ... More on stackoverflow.com
🌐 stackoverflow.com
How to randomize (shuffle) a JavaScript array? - Stack Overflow
This is a good display of the theory, ... an array. As it is, if you accidentally pass in a value of a different type, the while loop will never finish and the program will hang. 2022-01-11T22:32:25.093Z+00:00 ... do not add things like this into your code when libraries like lodah exists. Code bloat is a real danger, so use utility libraries when possible. geeksforgeeks.org/lodash-_-shuffle-method ... More on stackoverflow.com
🌐 stackoverflow.com
How to shuffle an array of objects in javascript? - Stack Overflow
In my experience, this works except for this one case: an associative array where every element is an array of objects. If I pass one of those array elements (which is itself an array) to this function, then the array is not shuffled. However, if you modify the code to make a copy of the array ... More on stackoverflow.com
🌐 stackoverflow.com
How To Shuffle Arrays
I'm not sure what the article is trying to say. The real reason to use proven shuffling algorithms is that most shuffling algorithms that people come up with are not truly random -- they introduce bias. You mention runtime complexity analysis, but don't actually analyze any of the functions you mention. Your first implementation has a worst case runtime of Θ(∞), whereas the Fisher Yates algorithm has a worst case runtime of Θ(n), so yes, that's an improvement, but the bigger problem is that without a formal proof, it's hard to know whether a randomization algorithm you come up with is correct. More on reddit.com
🌐 r/javascript
11
14
June 1, 2020
🌐
TutorialsPoint
tutorialspoint.com › home › lodash › lodash shuffle method
Lodash - shuffle method
January 20, 2021 - collection (Array|Object) − The collection to shuffle. ... var _ = require('lodash'); var list = [1, 2, 3, 4, 5] var result = _.shuffle(list); console.log(result);
Top answer
1 of 1
3

One simple approach is to just shuffle the array of indices and then use that to get both your arrays in the corresponding order:

const mp3 = ['sing.mp3','song.mp3','tune.mp3','jam.mp3'];
const ogg = ['sing.ogg','song.ogg','tune.ogg','jam.ogg'];

const indices = _.shuffle([0, 1, 2, 3]);

const shuffledMp3 = indices.map(idx => mp3[idx]);
const shuffledOgg = indices.map(idx => ogg[idx]);

console.log(shuffledMp3, shuffledOgg);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

However, you shouldn't need to do this. Your question only arises because you're storing the data in an unhelpful way. Since the elements of the two arrays are clearly linked to each other, you shouldn't store them as 2 arrays, but as a single array whose elements are objects holding both filenames as properties. This enables you to get what you want with a single shuffle:

const files = [{mp3: 'sing.mp3', ogg: 'sing.ogg'}, {mp3: 'song.mp3', ogg: 'song.ogg'}, {mp3: 'tune.mp3', ogg: 'tune.ogg'}, {mp3: 'jam.mp3', ogg: 'jam.ogg'}];

const shuffled = _.shuffle(files);

console.log(shuffled.map(file => file.mp3));
console.log(shuffled.map(file => file.ogg));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

(It's also worth noting that if all your file names are as predictably formed as in your example, even this is unnecessary - you can just store the "raw" filenames: ['sing', 'song', 'tune', 'jam'] and add whatever file extension you need at the point of needing it. But perhaps your real data is not so consistent.)

🌐
npm
npmjs.com › package › lodash.shuffle
lodash.shuffle - npm
August 13, 2016 - The lodash method `_.shuffle` exported as a module.. Latest version: 4.2.0, last published: 10 years ago. Start using lodash.shuffle in your project by running `npm i lodash.shuffle`. There are 145 other projects in the npm registry using lodash.shuffle.
      » npm install lodash.shuffle
    
Published   Aug 13, 2016
Version   4.2.0
Author   John-David Dalton
🌐
Tabnine
tabnine.com › home page › code › javascript › lodash
lodash.shuffle JavaScript and Node.js code examples | Tabnine
function getShuffledColorPalettesKeys() { return [...shuffle(Object.keys(colorPalettes))]; } LoDashStatic.map · Creates an array of values by running each element in collection through iteratee. The iteratee is · LoDashStatic.isEmpty · Checks if value is empty.
🌐
Byby
byby.dev › js-array-shuffle
How to shuffle an array in JavaScript
Calling _.shuffle() on an array in Lodash returns a new array with the elements randomly reordered.
🌐
Examplejavascript
examplejavascript.com › lodash › shuffle
How to use the shuffle function from lodash
lodash.shuffle takes an array as input and returns a new array with the same elements, but in a shuffled order.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › how-to-shuffle-an-array-in-a-random-manner-in-javascript
How to shuffle an array in a random manner in JavaScript?
The shuffle method processes our input array and displays the shuffled array. <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script> </head> <body> <h3> Shuffle a JavaScript array using ...
🌐
Netlify
netlify.com › blog › 2017 › 01 › 12 › common-javascript-functions-with-lodash
Common JavaScript functions with Lodash | Netlify
When I first started learning the ... in the Ruby and Python API, but are not available with JavaScript. Luckily there are libraries like Lodash that provides functions for solved problems like shuffling an array while delivering modularity....
🌐
Stack Abuse
stackabuse.com › shuffling-arrays-in-javascript
Shuffling Arrays in JavaScript
August 26, 2023 - This will output a shuffled ... properly. If you're using Lodash, a popular JavaScript utility library, you can shuffle arrays with the _.shuffle() function....
🌐
GitHub
github.com › lodash › lodash › issues › 28
Make `_.shuffle` work on objects. · Issue #28 · lodash/lodash
Underscore just fixed their _.shuffle to work with objects because internally they were using _.each and unintended object usage slipped in. This is kinda lame as it complicates things but I am wondering do you all think Lo-Dash should support this untested feature yet?
🌐
Crio
crio.do › blog › how-to-shuffle-array-in-javascript-2025-criodo
How to Shuffle an Array in JavaScript?
December 15, 2024 - In-place Shuffling: The Fisher-Yates algorithm modifies the original array, avoiding extra memory usage. Unbiased Randomization: Ensures all permutations of the array are equally likely. Using a Utility Library: Lodash provides a _.shuffle method.
Top answer
1 of 16
2621

The de-facto unbiased shuffle algorithm is the Fisher–Yates (aka Knuth) Shuffle.

You can see a great visualization here.

function shuffle(array) {
  let currentIndex = array.length;

  // While there remain elements to shuffle...
  while (currentIndex != 0) {

    // Pick a remaining element...
    let randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }
}

// Used like so
let arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);

2 of 16
1276

Here's a JavaScript implementation of the Durstenfeld shuffle, an optimized version of Fisher-Yates:

/* Randomize array in-place using Durstenfeld shuffle algorithm */
function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

It picks a random element for each original array element, and excludes it from the next draw, like picking randomly from a deck of cards.

This clever exclusion swaps the picked element with the current one, then picks the next random element from the remainder, looping backwards for optimal efficiency, ensuring the random pick is simplified (it can always start at 0).

Note the loop condition skips i==0, since j can only ever be 0 then, leading to no swap.

Algorithm runtime is O(n). Note that the shuffle is done in-place so if you don't want to modify the original array, first make a copy of it with .slice(0).


EDIT: Updating to ES6 / ECMAScript 2015

The new ES6 allows us to assign two variables at once. This is especially handy when we want to swap the values of two variables, as we can do it in one line of code. Here is a shorter form of the same function, using this feature.

function shuffleArray(array) {
    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]];
    }
}
🌐
DEV Community
dev.to › bybydev › how-to-shuffle-an-array-in-javascript-3efd
How to shuffle an array in JavaScript - DEV Community
May 16, 2024 - Calling _.shuffle() on an array in Lodash returns a new array with the elements randomly reordered.
🌐
Favtutor
favtutor.com › articles › shuffle-an-array-javascript
How to Shuffle an Array in JavaScript? (with code)
January 31, 2024 - 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.
🌐
Lodash
lodash.com › docs
Lodash Documentation
Creates an array of shuffled values, using a version of the Fisher-Yates shuffle.
🌐
Sling Academy
slingacademy.com › article › ways-to-shuffle-an-array-in-javascript
3 Ways to Shuffle an Array in JavaScript - Sling Academy
February 19, 2023 - 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' ] Lodash is a super popular multi-purpose Javascript open-source library.
🌐
TutorialsPoint
tutorialspoint.com › article › How-to-randomize-shuffle-a-JavaScript-array
How to randomize (shuffle) a JavaScript array?
The shuffle method processes our input array and displays the shuffled array. <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script> </head> <body> <h3> Shuffle a JavaScript array using ...