70

I have this array. How do I use underscore '_.sortBy' to sort it according to start date?

[
    { 
        id: 'oljw832021kjnb389xzll323jk',
        start: { dateTime: '2013-09-26T13:30:00-07:00' },
        end: { dateTime: '2013-09-26T14:30:00-07:00' },
    },
    { 
        id: 'ed7l5tmckdp0lm90nvr4is3d4c',
        start: { dateTime: '2013-09-26T15:30:00-07:00' },
        end: { dateTime: '2013-09-26T16:30:00-07:00' },
    },
    { 
        id: 'etmasdsackdp0kjl0nvrkopioqw',
        start: { dateTime: '2013-09-26T18:00:00-07:00' },
        end: { dateTime: '2013-09-26T19:00:00-07:00' },
    }
]

3 Answers 3

169

Use an iterator function, not a single string for a property:

_.sortBy(arr, function(o) { return o.start.dateTime; })
Sign up to request clarification or add additional context in comments.

7 Comments

it gives in ascending order, but how to sort it descending order of date ?
@RobinAT: You simply could negate the datetime
if you want to do descending order, then just do arr.reverse()
if you want descending order of date then use below _.sortBy(arr, function(o) { var dt = new Date(o.start.dateTime); return -dt; })
@imdadhusen: Yes, that's what I meant when I said "negate the datetime". However, that Date object is superfluous, you can just do return -o.start.dateTime;
|
2

I did it this way:

var sorted = _(list).sortBy(
                    function (item) {                        
                        return [new Date(item.effectiveDate).getTime(), item.batchId];
                    }), "batchId");

If you want it descending then it's the same thing but *-1

var sorted = _(list).sortBy(
                    function (item) {                        
                        return [new Date(item.effectiveDate).getTime()*-1, item.batchId];
                    }), "batchId");

In this example I am ordering by two fields, you can forget about the item.batchId.

Hope this helps someone.

Comments

1

var sortedItem = _.sortBy(yourArrayName, ["start"])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.