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:
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?
CodePudding user response:
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))
CodePudding user response:
Thanks everyone for answering! Turns out that I misunderstood. I tried printing the numbers, which is why they showed up without brackets and had seemingly lost their structure. You guys were right now, they didn't lose their structure, and it works as it should.