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

How do I shuffle a list of lists?

I’ve got a list of lists:

myList = [[67, 79], [1, 5], [63, 122], [43, 44], [2, 5], [31, 37], [16, 45], [110, 124], [60, 64], [68, 79], [37, 116], [5, 76]]

And I would like to shuffle it around, but every way I’ve tried to do it has ruined the structure of lists and stripped it down to bare numbers. For instance:

myShuffledList = myList.sort((a, b) => 0.5 - Math.random());

Gives me something like:

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

myShuffledList = [60,64,110,124,63,122,5,76,43,44,68,79,37,116,2,5,1,5,67,79,16,45,31,37]

instead of something like this:

myShuffledList = [[68, 79], [2, 5], [31, 37], [1, 5], [67, 79], [110, 124], [63, 122], [16, 45], [5, 76], [37, 116], [43, 44], [60, 64]]

Is there simple solution as to how I can avoid the list being stripped completely, and just shuffle the lists of lists?

>Solution :

Everything is working as you intended it to. You just got bamboozled by console.log converting your array to strings. If you use a custom toString function to avoid this you can see that everything works as intended

myList = [
  [67, 79],
  [1, 5],
  [63, 122],
  [43, 44],
  [2, 5],
  [31, 37],
  [16, 45],
  [110, 124],
  [60, 64],
  [68, 79],
  [37, 116],
  [5, 76]
]
myShuffledList = myList.sort((a, b) => 0.5 - Math.random());

var toString = (list) => {
  return `${list.map((sublist) => `[${sublist}]`)}`
}

console.log(toString(myList))
console.log(toString(myShuffledList))
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