Sort nested array by value?

落爺英雄遲暮 提交于 2019-12-11 03:45:31

问题


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]
]

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 ?


回答1:


You could use sortBy with a function to pick off the first elements of the inner arrays:

sortBy _.sortBy(list, iterator, [context])

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

So perhaps this:

_(data).sortBy(function(a) {
    return a[0];
});

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

You could also do this:

_(data).sortBy('0')

Demo: http://jsfiddle.net/ambiguous/mLDzH/



来源:https://stackoverflow.com/questions/15334015/sort-nested-array-by-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!