timothyylim
timothyylim

Reputation: 1527

Javascript | How to save order after randomizing an array

After randomizing an array of question elements I am trying to save the new indexes of the elements.

I use an array called idMap to do achieve this. It saves the original index in the first for loop then updates the index once the question elements array has been shuffled.

Is there better way to do this without saving the order as an attribute of the question (questionInstances[i].originalOrder) as it may be overwritten?

  // Save the original order of array
  for (var i = 0; i < questionInstances.length; i++) {
    questionInstances[i].originalOrder = i;
    idMap[i] = i;
  }

  // Randomize array

  if (params.randomQuestions) {

    questionInstances = H5P.shuffleArray(questionInstances);

    // Save new randomized order
    for (var i = 0; i < questionInstances.length; i++) {
      idMap[i] = questionInstances[i].originalOrder;
    }

  }

Upvotes: 0

Views: 87

Answers (2)

homam
homam

Reputation: 1975

Let's first map questionInstances to a new array of tuples (which their first element is the original item in the array and the second element is its index):

let questionInstances = ["a", "b", "c", "d", "e"] // for example

let tuples = questionInstances.map((o, i) => ([o, i]))

The items in this array are:

[["a", 0], ["b", 1], ["c", 2], ["d", 3], ["e", 4]]

We mapped our original questionInstances to a new array (which contains their indices) without modifying (mutating) its elements.

Now shuffle this array:

tuples = H5P.shuffleArray(tuples)

Now the shuffled questionInstances array is:

questionInstances = tuples.map(d => d[0])

And the index map:

let idMap = tuples.map(d => d[1])

Bonus: you can get questionInstances and idMap in a single step using reduce:

let [shuffledQuestionInstances, idMap] = tuples.reduce(
    (acc, [o, i]) => [acc[0].concat([o]), acc[1].concat([i])], 
    [[],[]]
  )

Upvotes: 1

nick
nick

Reputation: 1207

You could just use a scoped hash table, assuming the question instances have unique ids.

// update this as needed
var hash = {
    //id: order
};

Upvotes: 0

Related Questions