如何排序的列值2维数组? [英] How to sort 2 dimensional array by column value?
本文介绍了如何排序的列值2维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任何一个可以帮助我整理在JavaScript中一个2维数组?
Can any one help me sort a 2 dimensional Array in JavaScript?
有将在以下格式的数据:
It will have data in the following format:
[12, AAA]
[58, BBB]
[28, CCC]
[18, DDD]
这应该是这样的,当排序方式:
It should look like this when sorted:
[12, AAA]
[18, DDD]
[28, CCC]
[58, BBB]
所以基本上,由第一列进行排序。
So basically, sorting by the first column.
干杯
推荐答案
这是这个简单的:
var a = [[12, 'AAA'], [58, 'BBB'], [28, 'CCC'],[18, 'DDD']];
a.sort(sortFunction);
function sortFunction(a, b) {
if (a[0] === b[0]) {
return 0;
}
else {
return (a[0] < b[0]) ? -1 : 1;
}
}
我请你阅读文档。
如果你想在第二列进行排序,你可以这样做:
If you want to sort by the second column, you can do this:
a.sort(compareSecondColumn);
function compareSecondColumn(a, b) {
if (a[1] === b[1]) {
return 0;
}
else {
return (a[1] < b[1]) ? -1 : 1;
}
}
这篇关于如何排序的列值2维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文