I have an array in JavaScript.
var array = [[12,3],[10,2],[8,1],[12,3],[7,1],[6,1],[4,1],[10,2],[12,3]]
I would like to sort this array by the second value in descending order. The expected output is
[[12,3],[12,3],[12,3],[10,2][10,2],[8,1],[7,1],[6,1],[4,1]
I've tried
array.sort(function(array) {
return array[1] - array[1]
}
Unfortunately, that didn't work.
Sorting single-dimensional arrays is easy but I'm not sure how to do it with multi-dimensional arrays.
Any help will be appreciated.
Your syntax for the sort function is a bit off. Your function should take two parameters. The following sorts descending by the second position in the inner arrays.
var array = [[12,3],[10,2],[8,1],[12,3],[7,1],[6,1],[4,1],[10,2],[12,3]]; console.log(array.sort(function(a, b) { return b[1] - a[1]; }));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.