Array ordering based on the order of another array

Asked

Viewed 283 times

1

Next, I have two vectors each with a numerical 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 doubt is how I would order the values of Array1, making the order of the values equal to that of Array2. For example, in place of Array1 whose value is "1", it would put the value that is in the same position (index), only in Array2. In case he would trade for the "7". Anyway, someone would have a guess?

  • 2

    Your example arrays are equal. In this case the two would be equal.

  • This is exactly what I intend to do, @Miguel . I order array1 from the position of the same values in array2

2 answers

1

Since both arrays have the same values (although ordered differently), and the reordering of array 1 would leave 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, i.e.: the changes that are made in one will also affect the other. If you really want a copy, make it:

array1 = array2.slice(0);

Envious will say that both forms are cheating.

  • Bah, I didn’t know about this... I’m gonna use it right now.

  • 1

    @Gabrielpolidoro there are other ways: http://stackoverflow.com/questions/3978492/javascript-fastest-way-to-duplicate-an-array-slice-vs-for-loop This can be interesting because you can recognize them if you see them in other people’s code.

  • 1

    This will not be a true copy, as there are still pointers: https://jsfiddle.net/f1baf543/

1

If you only want two equal arrays you can do:

arrayA = arrayB;

or even

arrayA = arrayB.slice();

but this does not prevent elements of the array from being referenced from one array to the other, since they were not copied, but rather "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 the best is to pass to string and back to array. So create copies in depth

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" 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.