Shuffle multiple javascript arrays in the same way -


i've got 2 arrays

var mp3 = ['sing.mp3','song.mp3','tune.mp3','jam.mp3',etc]; var ogg = ['sing.ogg','song.ogg','tune.ogg','jam.ogg',etc]; 

i need shuffle both arrays come out same way, ex:

var mp3 = ['tune.mp3','song.mp3','jam.mp3','sing.mp3',etc]; var ogg = ['tune.ogg','song.ogg','jam.ogg','sing.ogg',etc]; 

there's few posts on stackoverflow shuffle arrays in different ways--this 1 pretty great--but none of them demonstrate how shuffle 2 arrays in same exact way.

thnx!

add argument fisher-yates shuffle. (assumes arrays equal length)

var mp3 = ["sing.mp3", "song.mp3"];  var ogg = ["sing.ogg", "song.ogg"];    function shuffle(obj1, obj2) {    var index = obj1.length;    var rnd, tmp1, tmp2;      while (index) {      rnd = math.floor(math.random() * index);      index -= 1;      tmp1 = obj1[index];      tmp2 = obj2[index];      obj1[index] = obj1[rnd];      obj2[index] = obj2[rnd];      obj1[rnd] = tmp1;      obj2[rnd] = tmp2;    }  }    shuffle(mp3, ogg);    console.log(mp3, ogg);

update:

if going support more arrays (as suggested in comments), modify fisher-yates follows (aswell perform checks make sure arguments of array , lengths match).

var isarray = array.isarray || function(value) {    return {}.tostring.call(value) !== "[object array]"  };    var mp3 = ["sing.mp3", "song.mp3", "tune.mp3", "jam.mp3"];  var ogg = ["sing.ogg", "song.ogg", "tune.ogg", "jam.ogg"];  var acc = ["sing.acc", "song.acc", "tune.acc", "jam.acc"];  var flc = ["sing.flc", "song.flc", "tune.flc", "jam.flc"];    function shuffle() {    var arrlength = 0;    var argslength = arguments.length;    var rnd, tmp;      (var index = 0; index < argslength; index += 1) {      if (!isarray(arguments[index])) {        throw new typeerror("argument not array.");      }        if (index === 0) {        arrlength = arguments[0].length;      }        if (arrlength !== arguments[index].length) {        throw new rangeerror("array lengths not match.");      }    }      while (arrlength) {      rnd = math.floor(math.random() * arrlength);      arrlength -= 1;      (argsindex = 0; argsindex < argslength; argsindex += 1) {        tmp = arguments[argsindex][arrlength];        arguments[argsindex][arrlength] = arguments[argsindex][rnd];        arguments[argsindex][rnd] = tmp;      }    }  }    shuffle(mp3, ogg, acc, flc);    console.log(mp3, ogg, acc, flc);


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -