[英]Sorting a 2d array JavaScript by value of both columns
How can I quickly sort a 2d array in JavaScript according to value of both columns?如何根据两列的值快速对 JavaScript 中的二维数组进行排序?
Array will appear in this format:数组将以这种格式出现:
[12, 3]
[12, 2]
[54, 43]
[32, 12]
After sorting it should look like this:排序后应该是这样的:
[12, 2]
[12, 3]
[32, 12]
[54, 43]
You can use Array.sort
and subtract the first items in the nested arrays to determine precedence.您可以使用
Array.sort
并减去嵌套 arrays 中的第一项来确定优先级。 If they're equal, subtract the second items.如果它们相等,则减去第二项。
const arr = [ [12, 3], [12, 2], [54, 43], [32, 12] ] const res = arr.sort((a,b) => a[0] - b[0] || a[1] - b[1]) console.log(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.