按值排序嵌套数组? [英] Sort nested array by value?
问题描述
我有一个嵌套数组如下所示:
I have a nested array like the following:
data = [
[Date.UTC(2013, 1, 1), 1],
[Date.UTC(2013, 1, 5), 22],
[Date.UTC(2013, 1, 2), 2],
[Date.UTC(2013, 1, 11), 33]
]
我使用下划线和我试图找出一个办法由 Date.UTC
这样的阵列显示了第一次约会到最后还是低到高进行排序它?
I am using underscore and I am trying to figure out a way to sort it by the Date.UTC
so the array shows dates by first to last or lowest to highest ?
推荐答案
您可以使用 sortBy
用函数摘下内部数组的第一要素:
You could use sortBy
with a function to pick off the first elements of the inner arrays:
sortBy _。sortBy(列表,迭代器,[背景])
返回列表后,运行通过的迭代每个值的结果升序排列的排序副本。迭代器也可能是属性的字符串名称排序(如长度
)。
Returns a sorted copy of list, ranked in ascending order by the results of running each value through iterator. Iterator may also be the string name of the property to sort by (eg. length
).
所以,这可能:
_(data).sortBy(function(a) {
return a[0];
});
由于 Data.UTC
给你一个数字,你可以在一个否定扔在相反的方向进行排序:
Since Data.UTC
gives you a number, you can throw in a negation to sort in the opposite direction:
_(data).sortBy(function(a) {
return -a[0];
});
您也可以这样做:
_(data).sortBy('0')
演示: http://jsfiddle.net/ambiguous/mLDzH/
这篇关于按值排序嵌套数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!