如何按列值对二维数组进行排序?

有人能帮我用 JavaScript 对二维数组进行排序吗?

它的数据格式如下:

[12, AAA]
[58, BBB]
[28, CCC]
[18, DDD]

排序时应该是这样的:

[12, AAA]
[18, DDD]
[28, CCC]
[58, BBB]

So basically, sorting by the first column.

干杯

241421 次浏览

试试这个:

//WITH FIRST COLUMN
arr = arr.sort((a, b) => a[0] - b[0]);


//WITH SECOND COLUMN
arr = arr.sort((a, b) => a[1] - b[1]);

Note: Original answer used a greater than (>) instead of minus (-) which is what the comments are referring to as incorrect.

就这么简单:

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;
}
}

我邀请你去 阅读文件

如果想按第二列排序,可以这样做:

a.sort(compareSecondColumn);


function compareSecondColumn(a, b) {
if (a[1] === b[1]) {
return 0;
}
else {
return (a[1] < b[1]) ? -1 : 1;
}
}

最好的方法是使用以下内容,因为第一列中可能有重复的值。

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]
});

如果您和我一样,不会希望每次更改排序所依据的列时都要更改每个索引。

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);

没什么特别的,只是节省了从数组中返回某个索引值所需的成本。

function sortByCol(arr, colIndex){
arr.sort(sortFunction)
function sortFunction(a, b) {
a = a[colIndex]
b = b[colIndex]
return (a === b) ? 0 : (a < b) ? -1 : 1
}
}
// Usage
var a = [[12, 'AAA'], [58, 'BBB'], [28, 'CCC'],[18, 'DDD']]
sortByCol(a, 0)
console.log(JSON.stringify(a))
// "[[12,"AAA"],[18,"DDD"],[28,"CCC"],[58,"BBB"]]"

由于我的用例涉及到几十个列,所以我稍微扩展了一下@jahroy 的回答。(也刚刚意识到@Charles-Clayton 也有同样的想法。)
我传递我想要进行排序的参数,排序函数被重新定义为进行比较所需的索引。

var ID_COLUMN=0
var URL_COLUMN=1


findings.sort(compareByColumnIndex(URL_COLUMN))


function compareByColumnIndex(index) {
return function(a,b){
if (a[index] === b[index]) {
return 0;
}
else {
return (a[index] < b[index]) ? -1 : 1;
}
}
}

使用箭头函数,并按第二个字符串字段排序

var a = [[12, 'CCC'], [58, 'AAA'], [57, 'DDD'], [28, 'CCC'],[18, 'BBB']];
a.sort((a, b) => a[1].localeCompare(b[1]));
console.log(a)

站在 Charles-clayton 和@vikas-gautam 的肩膀上,我添加了字符串测试,如果一个列像 OP 中一样有字符串,那么就需要这个测试。

return isNaN(a-b) ? (a === b) ? 0 : (a < b) ? -1 : 1 : a-b  ;

测试 isNaN(a-b)确定字符串是否不能被强制为数字。如果他们可以,那么 a-b测试是有效的。

注意,对混合类型的列进行排序总是会得到有趣的结果,因为严格的相等测试 (a === b)总是返回 false。 在这里看 MDN

这是 Logger 测试的完整脚本-使用 GoogleApps 脚本。

function testSort(){


function sortByCol(arr, colIndex){
arr.sort(sortFunction);
function sortFunction(a, b) {
a = a[colIndex];
b = b[colIndex];
return isNaN(a-b) ? (a === b) ? 0 : (a < b) ? -1 : 1 : a-b  ;  // test if text string - ie cannot be coerced to numbers.
// Note that sorting a column of mixed types will always give an entertaining result as the strict equality test will always return false
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness


}
}
// Usage
var a = [ [12,'12', 'AAA'],
[12,'11', 'AAB'],
[58,'120', 'CCC'],
[28,'08', 'BBB'],
[18,'80', 'DDD'],
]
var arr1 = a.map(function (i){return i;}).sort();  // use map to ensure tests are not corrupted by a sort in-place.


Logger.log("Original unsorted:\n     " + JSON.stringify(a));
Logger.log("Vanilla sort:\n     " + JSON.stringify(arr1));
sortByCol(a, 0);
Logger.log("By col 0:\n     " + JSON.stringify(a));
sortByCol(a, 1);
Logger.log("By col 1:\n     " + JSON.stringify(a));
sortByCol(a, 2);
Logger.log("By col 2:\n     " + JSON.stringify(a));


/* vanilla sort returns " [
[12,"11","AAB"],
[12,"12","AAA"],
[18,"80","DDD"],
[28,"08","BBB"],
[58,"120","CCC"]
]
if col 0 then returns "[
[12,'12',"AAA"],
[12,'11', 'AAB'],
[18,'80',"DDD"],
[28,'08',"BBB"],
[58,'120',"CCC"]
]"
if col 1 then returns "[
[28,'08',"BBB"],
[12,'11', 'AAB'],
[12,'12',"AAA"],
[18,'80',"DDD"],
[58,'120',"CCC"],


]"
if col 2 then returns "[
[12,'12',"AAA"],
[12,'11', 'AAB'],
[28,'08',"BBB"],
[58,'120',"CCC"],
[18,'80',"DDD"],
]"
*/


}

一句话:

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)
}

If you want to sort based on first column (which contains 号码 value), then try this:

arr.sort(function(a,b){
return a[0]-b[0]
})

如果要根据第二列(其中包含 绳子值)进行排序,请尝试这样做:

arr.sort(function(a,b){
return a[1].charCodeAt(0)-b[1].charCodeAt(0)
})

另外,对于第二种情况,需要比较它们的 ASCII 值。

好主意,萨比尔・艾哈迈德,但只能按第一个字母排序,第三个字母:

array.sort((a, b) => (a[n].charCodeAt(0)*1000000 + a[n].charCodeAt(1)*1000 + a[n].charCodeAt(2)) - (b[n].charCodeAt(0)*1000000 + b[n].charCodeAt(1)*1000 + b[n].charCodeAt(2)));
Solution vary depend on column value is numeric or string.


To sort by first column if value is numeric,
array.sort( (a, b) => a[0] - b[0]);


To sort by second column if value is numeric,
array.sort( (a, b) => a[1] - b[1]);


To sort by first column if value is string/letter,
array.sort( function(a, b) {
const nameA = a[0].toUpperCase(); // to avoid case while sort
const nameB = b[0].toUpperCase();
if(nameA > nameB)
return 1;
else if(nameB > nameA)
return -1;
else
return 0;
})

指定排序顺序和列的二维数组排序。 默认顺序0意味着没有更改,因此必须指定顺序: 1 = > 升序,-1 = > 降序。默认列为0。

let sort2d = (arr2d = [], order = 0, column = 0) => {
if (column < 0 || column > 1) {
if (order == 1)
return arr2d.sort((a, b) => a[column] - b[column])
if (order == -1)
return arr2d.sort((a, b) => b[column] - a[column])
}
return arr2d
}


let arr2d = [ [5, 3], [2, 5], [9, 1], [4, 1] ]
console.log(sort2d(arr2d, 1, -1)) //  [ [ 2, 5 ], [ 5, 3 ], [ 9, 1 ], [ 4, 1 ] ]


我使用 sort 对数组进行排序

这是我的暗号:

const sortArr = (arr) => {
arr.sort((valA, valB) => valA[0] - valB[0])
return arr
}


const arr = [
[12, 'AAA'],
[58, 'BBB'],
[28, 'CCC'],
[18, 'DDD']
]
console.log(sortArr(arr))