+ 3

JavaScript sort 2D array

So I have an array in JS which looks something like this: let arr = [["p1",5],["p2",7],["p3",2]] How would I sort it in descending order by the second value? So that it would look like this: [["p3",2],["p1",5],["p2",7]] Thanks!

21st Aug 2019, 8:49 AM
Paul Grasser
Paul Grasser - avatar
3 Answers
+ 6
let sorted = arr.sort((a,b) => a[1] - b[1]); https://code.sololearn.com/WLQdSKrduwtm/?ref=app
21st Aug 2019, 9:23 AM
CalviŐČ
CalviŐČ - avatar
+ 3
By the way, your specifications is ascending order instead of descending order.
21st Aug 2019, 3:08 PM
Gordon
Gordon - avatar
+ 2
Thank you! 😁
21st Aug 2019, 9:32 AM
Paul Grasser
Paul Grasser - avatar