Reputation: 49
I'm using javascript and trying to sync two arrays so that both arrays have the same index location.
var array1 = ["word1","word2","word3","word4","word5"];
var array2 = [1,2,3,4,5];
array2.sort(function(){ return Math.random() -.5});
This scrambles array2 into something like [2,3,1,5,4]
Now I need array1 to get the same order: ["word2", "word3", "word1", "word 5", "word4"]
How can I do this?
Upvotes: 0
Views: 651
Reputation: 22421
You will need to link values in both arrays together. Easy way to do so is to put them in third array so pairs[index] = [ array1[index], array2[index] ]
. Sort this pairs array just as you did and then split pairs back into your original arrays.
Upvotes: 0
Reputation: 16595
you will be better of using a different structure. i.e
[{k: 1, v:'word1'}, {k: 2, v:'word2'}]
and sorting that instead
Upvotes: 2
Reputation: 43243
Something like this should be a pretty simple way to do it:
//assume array1 is like in your example and
//array2 is the result of the randomization
var result = [];
for(var i = 0; i < array2.length; i++) {
result[i] = array1[array2[i]];
}
Upvotes: 0
Reputation: 9022
Use associative arrays. Then shuffle the keys (eventually as a third array) and rearrange the first two array accordingly.
EDIT: Sorry, I read this as PHP and not javascript. My mistake. Maybe use objects instead of arrays.
Upvotes: 0