Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort 2D array by matching the last values with the first one in the next index

So basically, I have this array

array = [[1,0],[2,1],[0,3],[3,2]]

Is there any quick method to convert the array to look like this

array = [[0,3],[3,2],[2,1],[1,0]]

What I want is for the first element of the new array to be always contain 0 in the first spot of the nested array. That’s easy enough, because the sort() function does exactly that; the hard part is ordering the new array like the one above.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In the most simplest terms, I’d like for nested arrays to be "connected": see how the 3 of the first nested array matches the other 3 to its right and so on.

Feel free to leave any comments so I can try to explain the problem a little bit better.

>Solution :

For the example you gave the easiest solution would be to sort the 2d array by the second element of each inner array, as follow:

let array = [[1,0],[2,1],[0,3],[3,2]];
array.sort((a, b) => b[1] - a[1]);

In that way you can sort the array with the sort method according to the elements in the inner arrays.

let array = [[1,0],[2,1],[0,3],[3,2]];
array.sort((a, b) => b[1] - a[1]);
console.log(array);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading