Ale*_*lex 68 javascript arrays sorting multidimensional-array
任何人都可以帮助我在JavaScript中对二维数组进行排序吗?
它将具有以下格式的数据:
[12, AAA]
[58, BBB]
[28, CCC]
[18, DDD]
Run Code Online (Sandbox Code Playgroud)
排序时应该如下所示:
[12, AAA]
[18, DDD]
[28, CCC]
[58, BBB]
Run Code Online (Sandbox Code Playgroud)
基本上,按第一列排序.
干杯
jah*_*roy 89
这很简单:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我邀请您阅读文档.
如果要按第二列排序,可以执行以下操作:
a.sort(compareSecondColumn);
function compareSecondColumn(a, b) {
if (a[1] === b[1]) {
return 0;
}
else {
return (a[1] < b[1]) ? -1 : 1;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 52
最好的方法是使用以下内容,因为第一列中可能存在重复值.
var arr = [[12, 'AAA'], [12, 'BBB'], [12, 'CCC'],[28, 'DDD'], [18, 'CCC'],[12, 'DDD'],[18, 'CCC'],[28, 'DDD'],[28, 'DDD'],[58, 'BBB'],[68, 'BBB'],[78, 'BBB']];
arr.sort(function(a,b) {
return a[0]-b[0]
});
Run Code Online (Sandbox Code Playgroud)
PSR*_*PSR 42
试试这个
//WITH FIRST COLUMN
arr = arr.sort(function(a,b) {
return a[0] - b[0];
});
//WITH SECOND COLUMN
arr = arr.sort(function(a,b) {
return a[1] - b[1];
});
Run Code Online (Sandbox Code Playgroud)
注意:原始答案使用大于(>)而不是减号( - ),这是注释所指的不正确.
如果您和我一样,每次要更改要排序的列时,都不希望更改每个索引.
function sortByColumn(a, colIndex){
a.sort(sortFunction);
function sortFunction(a, b) {
if (a[colIndex] === b[colIndex]) {
return 0;
}
else {
return (a[colIndex] < b[colIndex]) ? -1 : 1;
}
}
return a;
}
var sorted_a = sortByColumn(a, 2);
Run Code Online (Sandbox Code Playgroud)
如果您想根据第一列(包含数值)进行排序,请尝试以下操作:
arr.sort(function(a,b){
return a[0]-b[0]
})
Run Code Online (Sandbox Code Playgroud)
如果您想根据第二列(包含字符串值)进行排序,请尝试以下操作:
arr.sort(function(a,b){
return a[1].charCodeAt(0)-b[1].charCodeAt(0)
})
Run Code Online (Sandbox Code Playgroud)
PS对于第二种情况,你需要比较它们的ASCII值。
使用箭头功能,并按第二个字符串字段排序
var a = [[12, 'CCC'], [58, 'AAA'], [57, 'DDD'], [28, 'CCC'],[18, 'BBB']];
a.sort((a, b) => a[1].localeCompare(b[1]));
console.log(a)
Run Code Online (Sandbox Code Playgroud)
在一行中:
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
]
function myFunction() {
return cars.sort((a, b)=> a.year - b.year)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
142737 次 |
最近记录: |