How to make array2 have the same relation between the indexes after the shuffle of array1

2
  

array1 = [1,2,3];
  array2 = ["one", "two", "three"];

array1 and array2 have a direct relationship between indexes.

  

Shuffled array1 - > array1 = [3,1,2];

How to make array2 have the same relation between the indexes after the shuffle of array1, to be as for example:

  

array2 = ["three", "one", "two"]?

link

    array1 = [1,2,3];
    array2 = ["um","dois","três"];
    //Relação dos arrays entre os índices

    document.write(array1);
    document.write('<br />');
    document.write(array2);


    // embaralhou array1
    array1 = [3,1,2];
    document.write('<br /><br /><br />');
    document.write(array1);


    // Como ficar o array2 = ["três","um","dois"] a partir do embaralhamento do array1;
    
asked by anonymous 29.07.2016 / 00:51

1 answer

1

See if this is what you wanted:

First I created an object in which the keys correspond to the first array and their values correspond to the second array:

var corresp = {};
array1.forEach(function(el, i) {
  corresp[el] = array2[i];
});

I'd rather have it

{
    "1": "um",
    "2": "dois",
    "3": "três"
}

And after shuffling array1, simply redo the second array from the

// embaralhou array1
array1 = [3, 1, 2];

array1.forEach(function(el, i){
  array2[i] = corresp[el];
})

Result:

array1 = [1, 2, 3];
array2 = ["um", "dois", "três"];
//Relação dos arrays entre os índices
var corresp = {};
array1.forEach(function(el, i) {
  corresp[el] = array2[i];
})
document.body.innerHTML += (array1);
document.body.innerHTML += ('<br />');
document.body.innerHTML += (array2);

// embaralhou array1
array1 = [3, 1, 2];

array1.forEach(function(el, i) {
  array2[i] = corresp[el];
})
document.body.innerHTML += ('<br /><br /><br />');
document.body.innerHTML += (array1);
document.body.innerHTML += ('<br />');
document.body.innerHTML += (array2);

If you prefer a function:

 function match(array1, array1Sorted, array2) {
   var match = {};
   array1.forEach(function(el, i) {
     match[el] = array2[i];
   })
   array1Sorted.forEach(function(el, i) {
     array2[i] = match[el];
   })
   return array2;
 }

 var ar1 = [1, 2, 3, 4, 5, 6, 7];
 var ar2 = ['um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete'];
 var ar1sorted = [7, 3, 4, 2, 1, 5, 6];


document.body.innerHTML += ar1sorted;
document.body.innerHTML += "<br>";
document.body.innerHTML += match(ar1, ar1sorted, ar2);
    
29.07.2016 / 01:19