Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Shuffle nested arrays in Javascript

I’m trying to sort multiple arrays within an array (which also has to be shuffled). A simplified example is:

let toShuffle = [
[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5],
[10, 67, 19 ,27]
...
];

const shuffled = shuffle(toShuffle);

// outout would look something like:
// [
//   [8, 6, 5, 7, 9],
//   [4, 3, 1, 5, 2],
//   [19, 26, 10, 67],
//   ...
// ]

This needs to be flexible, so any number of arrays with any amount of values should be valid.

Here is what I’ve tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function shuffle(a) {
  for (let e in a) {
    if (Array.isArray(a[e])) {
      a[e] = shuffle(a[e]);
    } else {
      a.splice(e, 1);
      a.splice(Math.floor(Math.random() * a.length), 0, a[e]);
    }
  }

  return a;
}

console.log("Shuffled: " + shuffle([
  [1, 2, 3, 4, 5],
  [5, 4, 3, 2, 1]
]))

But it’s not working as intended. Is their an easier way to do this? Or is my code correct and just buggy.

>Solution :

You almost got it. The problem is that you are removing one item from an array, instead of capturing the removed item and them placing in a random position:

let toShuffle = [
[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5],
[10, 67, 19 ,27]
];

function shuffle(a) {
  a = [...a]; //clone array
  for (let e in a) {
    if (Array.isArray(a[e])) {
      a[e] = shuffle(a[e]);
    } else {
      a.splice(~~(Math.random() * a.length), 0, a.splice(e, 1)[0]);
    }
  }

  return a;
}

console.log(JSON.stringify(shuffle(toShuffle)))
console.log(JSON.stringify(toShuffle))

[EDIT]
The original code did not shuffle the parent array, if you need shuffle everything recursively, you can use this:

let toShuffle = [
[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5],
[10, 67, 19 ,27]
];

function shuffle(a) {
  a = a.map(i => Array.isArray(i) ? shuffle(i) : i); //clone array
  a.sort(i => ~~(Math.random() * 2) - 1); //shuffle
  return a;
}

console.log("shuffled", JSON.stringify(shuffle(toShuffle)))
console.log("original", JSON.stringify(toShuffle))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading