2

i have this json:

    module.exports = [
         {
           "date": "01-2012"
         },
         {
           "date": "12-2011"
         },
         {
           "date": "01-2014"
         },
         {
           "date": "08-2015"
         }
    ];

And i want sort by date, but the problem is that is not a valid format (MM-YYYY), this is possible? Can someone give me a hand here?

Thanks.

2
  • Where are you trying to sort this? In the backend? Could you explain better what you're doing, maybe showing more of your code? Commented Aug 29, 2015 at 18:38
  • Yes, i'm trying to export in the backend, with javascript (node.js). Commented Aug 29, 2015 at 20:10

1 Answer 1

2

Yes it's possible! To sort that array you can use the sort method of an array passing it the callback you want to use to sort it.

In your example you can do the following:

function parseMyDate( date_value ) {
    return new Date( date_value.replace(/([0-9]{1,2})\-([0-9]{4})/, "$2-$1-01") );
}

module.exports.sort(function(a, b) {
    return parseMyDate( a.date ) - parseMyDate( b.date );
});

Here you have a running example https://jsfiddle.net/un79c12m/ including the solution.

I hope it helps.

Sign up to request clarification or add additional context in comments.

2 Comments

rdgfuentes, thanks very much, but.. if i'm not asking to much, could you explain the regex? i understand the capture group, but i want understand what is $2-$1-01.
Sure! $2 contains what was captured in the second parenthesis in your case YYYY. On the other hand $1 contains what is captured by the regex in the first parenthesis this is MM in your case. Then I'm adding 01 for the day part so I can have a string date in ISO format to create an instance of a Date. Eg: "12-2011" will be converted to "2011-12-01" to create the Date object this is: new Date( '2011-12-01'). Makes sense?

Your Answer

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