Array sorting based on the order of another array

1

Next, I have two vectors each with a numeric sequence. Let's call them Array1 and Array2 . The values are below ...

Array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; Array2 = [7, 6, 3, 9, 4, 5, 1, 10, 8, 2];

My question is how I would sort Array1 values, making the order of values equal to Array2. For example, in place of Array1 whose value is "1", it would put the value that is in the same position (index), but in Array2. In case he would trade for "7". Anyway, would anyone have a hunch?

    
asked by anonymous 17.04.2017 / 13:21

2 answers

2

If you want only two equal arrays you can do:

arrayA = arrayB;

or even

arrayA = arrayB.slice();

This does not prevent array elements from being referenced from one array to another, since they were not copied, but "pointed".

Example:

var array1 = [{id:1, desc: 'foo'}, {id:2, desc: 'bar'}];
var array2 = array1.slice();

array1[0].desc = 'olé!';
console.log(array2[0]); // vai dar "olé" apesar de estar na array da cópia

If you have an array of Primitive elements it is best to pass to string and back to array. This creates deep copies

Example:

var array1 = [{id:1, desc: 'foo'}, {id:2, desc: 'bar'}];
var array2 = JSON.parse(JSON.stringify(array1));

array1[0].desc = 'olé!';
console.log(array2[0]); // vai dar "foo" 
    
17.04.2017 / 13:58
0

Since both arrays have the same values (though sorted differently), and the array 1 reordering would make it "equivalent" to array two, you could do this:

array1 = array2;

But in this way the two arrays will be clones, that is, the same collection of numbers, ie changes that are made in one will also affect the other. If you really want a copy, do it:

array1 = array2.slice(0);

Envy will tell you that both forms are cheating.

    
17.04.2017 / 13:25