+ 3

Shuffling JavaScript Array

Suppose I have an array like: a = ['a', 'l', 'e', 'r', 't'] I need a function to shuffle that array without changing forgetting the index of the values. Eg, this is the original array. a = ['a', 'l', 'e', 'r', 't'] ar = a[0] + a[1] + a[2] + a[3] + a[4] //ar = alert After random shuffle of array values, it may look like: a = ['t', 'e', 'a', 'r', 'l'] ar =a[2] + a[4] + a[1] + a[4] + a[0] //ar = alert Here, the value of "ar" should be same on every shuffle. /*The function can return these 2 statements as a string, but not necessarily needed*/

2nd Jan 2021, 10:38 AM
Bibek Oli
Bibek Oli - avatar
2 Answers
+ 3
There are many ways of saving original indexes for an array... However, your purpose/context is too vague to tell you wich is enough, wich is overkill or wich is better suited for your use case ^^ You could handle it with a 2d array if you wish, or even 2 separate arrays, or still even an array of objects holding value and original indexes and so on up to a specific custom class extending builtin Array class... So, if you have already an idea of how to handle this (2d array you're suggesting), why not starting by code your own function and ask for help with a more focused context as your code attempt ? Else, at least provide the (contextual) reason of your needs and a better description of the task to be done (ie: does your array always hold unique values or not, only unique char or any string length, or any type...) ^^ A quick attempt of my own, a few generic... could be improved/simplified depending of what you exactly want ;P https://code.sololearn.com/WTT17AMWP0Pv/?ref=app
3rd Jan 2021, 4:06 AM
visph
visph - avatar
+ 2
Is it not enought to have two dimensionsl array which has in one row values and in the other row originally indexes?
2nd Jan 2021, 11:10 AM
JaScript
JaScript - avatar