vendredi 21 août 2020

Parallel randomization/shuffle two arrays in Javascript

I have a Javascript object that looks like this (not defined as a variable because it is within an array alongside other similar objects):

 { //my_dict
  fruit: [[Apple, Banana, Grapes, Apple, Grapes, Grapes], [Banana, Apple, Apple, Kiwi, Grapes, Banana]]
  drink: [smoothie, juice],[juice],    
 },

I need to take one of the arrays in fruit (randomly) and assign it to a new key fruit_left: within my object and the other one to a new key fruit_right:. I also need to assign each of the arrays in drink: to new keys, say drink_left: and drink_right:. Now, the important thing is that I need to preserve the order so that if the first array in the original array fruit: becomes my fruit_left, then the first list in the original array drink: gets assigned to drink_left:, and vice versa.

I know it might sound confusing, but the way I have stored my data makes sense within the rest of my script, so I would really prefer to leave it that way. I was thinking of shuffling a list and then picking item [0] for my left side and [1] for my right side, but then I don't know how to make sure the drinks are shuffled in the same exact way. Is there a way to parallel shuffle? Both fruit and drink only have 2 items. Or perhaps is there a way to store what the original fruit array was and then use that information to infer the new order of drink? Thank you so much!

Note: I am trying to shuffle the order of the arrays, not the order of the items within them.




Aucun commentaire:

Enregistrer un commentaire