假设我有一个看起来像这样的数组:
var array = [["This should be last", 1],
["This should be first I think", 1],
["This is the middle one", 1]];
每个辅助数组的第二个值(在本例中始终为 1)对于排序是任意的。现在显然 .sort()
在这里没有直接用处。 (或者也许会?)
我需要对数组进行从最大到最小字符串大小的排序。因此,在排序过程之后,它应该如下所示:
var array = [["This should be first I think", 1],
["This is the middle one", 1]
["This should be last", 1]];
我该如何去做呢?
最佳答案
当您使用sort
时,您可以提供自定义比较函数:
array.sort(function(a,b) {
return b[0].length - a[0].length;
});
在 ECMAScript 6 中,可以简化为
array.sort((a,b) => b[0].length - a[0].length);
关于javascript - 根据辅助数组中的第一个字符串从最大到最小字符串大小对二维数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31921686/