javascript 如何按列值对二维数组进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16096872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort 2 dimensional array by column value?
提问by Alex
Can any one help me sort a 2 dimensional Array in JavaScript?
有人可以帮我在 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.
所以基本上,按第一列排序。
Cheers
干杯
回答by jahroy
It's this simple:
就这么简单:
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;
}
}
I invite you to read the documentation.
我邀请您阅读文档。
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;
}
}
回答by Pramod Vemulapalli
The best approach would be to use the following, as there may be repetitive values in the first column.
最好的方法是使用以下内容,因为第一列中可能有重复的值。
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]
});
回答by PSR
try this
试试这个
//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];
});
Note: Original answer used a greater than (>) instead of minus (-) which is what the comments are referring to as incorrect.
注意:原始答案使用了大于 (>) 而不是减号 (-),这就是评论所指的不正确。
回答by Dinesh Rajan
Using the arrow function, and sorting by the second string field
使用箭头函数,并按第二个字符串字段排序
var a = [[12, 'CCC'], [58, 'AAA'], [57, 'DDD'], [28, 'CCC'],[18, 'BBB']];
a.sort((a, b) => a[1].localeCompare(b[1]));
console.log(a)
回答by Charles Clayton
If you're anything like me, you won't want to go through changing each index every time you want to change the column you're sorting by.
如果你和我一样,你不会想在每次想要更改排序所依据的列时都更改每个索引。
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);
回答by Vikas Gautam
Nothing special, just saving the cost it takes to return a value at certain index from an array.
没什么特别的,只是节省了从数组中返回某个索引处的值所需的成本。
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"]]"
回答by Jared
in one line:
在一行中:
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)
}
回答by olamotte
As my usecase involves dozens of columns, I expanded @jahroy's answer a bit. (also just realized @charles-clayton had the same idea.)
I pass the parameter I want to sort by, and the sort function is redefined with the desired index for the comparison to take place on.
由于我的用例涉及数十列,因此我稍微扩展了@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;
}
}
}
回答by DeeKay789
Standing on the shoulders of charles-clayton and @vikas-gautam, I added the string test which is needed if a column has strings as in OP.
站在 charles-clayton 和 @vikas-gautam 的肩膀上,我添加了字符串测试,如果一列有字符串,就像 OP 一样。
return isNaN(a-b) ? (a === b) ? 0 : (a < b) ? -1 : 1 : a-b ;
The test isNaN(a-b)
determines if the strings cannot be coerced to numbers. If they can then the a-b
test is valid.
该测试isNaN(a-b)
确定字符串是否不能强制为数字。如果可以,则a-b
测试有效。
Note that sorting a column of mixed types will always give an entertaining result as the strict equality test (a === b)
will always return false.
See MDN here
请注意,对混合类型的列进行排序将始终给出有趣的结果,因为严格相等测试(a === b)
将始终返回 false。
在此处查看 MDN
This is the full script with Logger test - using Google Apps Script.
这是带有 Logger 测试的完整脚本 - 使用 Google Apps 脚本。
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"],
]"
*/
}