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 ?
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/