ericsicons
ericsicons

Reputation: 1495

Javascript sort array of objects in reverse chronological order

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

Upvotes: 1

Views: 2231

Answers (1)

RobG
RobG

Reputation: 147453

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

Upvotes: 3

Related Questions