javascript按子列表第二项对列表进行排序 [英] javascript sort list of lists by sublist second entry
本文介绍了javascript按子列表第二项对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何按最后一个元素的顺序对列表列表进行排序?
How can I sort a list of lists by order of the last element?
这是迄今为止我最好的尝试:
Here is my best attempt so far:
var mylist = [ [1, 'c'], [3, 'a'], [5, 'b']];
mylist.sort(function(a,b){return a[1]-b[1];});
我对sort
的呼叫无效,并且mylist
保持相同的顺序.
My call to sort
has not effect, and mylist
remains in the same order.
推荐答案
var mylist = [ [1, 'c'], [3, 'a'], [5, 'b']];
mylist.sort(function(a,b){return a[1].localeCompare(b[1]);});
console.log(mylist)
使用a[1].localeCompare(b[1])
以升序对列表进行排序,或者使用b[1].localeCompare(a[1])
进行其他排序.这样,您将比较两个字符串.您试图从另一个字符串中减去一个字符串,该字符串返回NaN
.
Use a[1].localeCompare(b[1])
to sort the list in the ascending order or b[1].localeCompare(a[1])
for other way round. This way you will be comparing two strings. You were trying to subtract one string from the other which return NaN
.
这篇关于javascript按子列表第二项对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文