1

I have an array of objects which holds a list of jobs and I would like to sort them in reverse chronological order as they would appear on a resume for example. I came up with the below solution which 'seems' to work but I was wondering if there is a better way of doing it.

The data I get back from the server is in the following format.

// ms=> monthStart me=>monthEnd etc...
var jobs = [
    {
        ms: 06,
        ys: 2013,
        me: 02,
        ye: 2015
    },
    {
        ms: 09,
        ys: 2013,
        me: 02,
        ye: 2014
    },
    {
        ms: 08,
        ys: 2000,
        me: 06,
        ye: 2016
    },
    {
        ms: 01,
        ys: 2014,
        me: 02,
        ye: 2017
    }
];

I came up with the function which adds a time order hash value to each item.

var args = {
    monthStart: 'ms',
    yearStart: 'ys',
    monthEnd: 'me',
    yearEnd: 'ye'
};

function createItemTimeOrder(item, args) {
    var monthStart = item[args.monthStart] || 0,
            yearStart = item[args.yearStart] || 0,
            monthEnd = item[args.monthEnd] || 0,
            yearEnd = item[args.yearEnd] || 0;

    // present if end month and end year are empty
    (monthEnd && yearEnd) || (monthEnd = 12, yearEnd = 3000);

    // weights yearEnd > monthEnd > yearStart > monthStart
    item._timeorder =
            monthStart + (yearStart * 2) +
            ((monthEnd + yearEnd) * 2) +
            (yearEnd * 4);
}

//add _timeorder  proptery
jobs.forEach(function (job) {
    createItemTimeOrder(job, args);
});

// sortby timer order in in reverse chronological order
jobs.sort(function (job1, job2) {
    return job2._timeorder - job1._timeorder;
});
1
  • Why not use Array.prototype.sort() with your custom compareFunction? Commented Jun 22, 2015 at 4:08

1 Answer 1

3

As PM 77-1 suggests, consider using the built–in Array.prototype.sort with Date objects. Presumably you want to sort them on one of start or end:

jobs.sort(function(a, b) {
  return new Date(a.ys, a.ms-1) - new Date(b.ys, b.ms-1);
})
Sign up to request clarification or add additional context in comments.

1 Comment

It also seems plausible that you would want to break ties by the other date, so you may want to edit that in as well.

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.