NodeDeveloper102 NodeDeveloper102 - 5 months ago 22
Javascript Question

tracking indexes with a shuffle algorithm in javascript

I have an simple array of strings that looks like the one below and a corresponding new array. What I need to accomplish is to is to shuffle the the simple array with a simple shuffle algorithm (like the one below), but I need the corresponding new array to to be shuffled with the same exact shuffle, that is the result of each index would be identical. That may be confusing so look at the example output below and it should become clear. Is this type of algorithm even possible with Fisher-Yates shuffle?

Fiddle: here

Before:

var simple_arr = ["701", "702", "703", "704", "705", "706", "707", "708"];
var new_arr = ["A1","A2","A3","A4","A5","A6","A7","A8"];


After:

var after_simple_arr = ["701", "708", "702", "705", "703", "706", "704", "707"];
var after_new_arr = ["A1","A8","A2","A5","A3","A6","A4","A7"];


Fisher-Yates shuffle algorithm:

function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;

// While there remain elements to shuffle...
while (0 !== currentIndex) {

// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;

// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}

Answer

You could shuffle an index array then use it as the index for the two arrays you care about:

var ids = [];
for (var i = 0; i < simple_arr.length; i++) {
    ids.push(i);
}
ids = shuffle(ids);
var dat1 = [];
var dat2 = [];
for (var i = 0; i < ids.length; i++) {
    dat1.push(simple_arr[ids[i]]);
  dat2.push(new_arr[ids[i]]);
}
console.log("shuffled simple_arr: ", dat1);
console.log("shuffled new_arr: ", dat2);