Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a JSON object in JavaScript and I am trying to sort the object in order by dates.

fileListObj[id] = date;

 output : "#HIDDEN ID": "16/12/2013"

How can I sort the object to be in order by most recent date?

I only know how to do this in php

share|improve this question

3 Answers 3

include moment.js

fileListObj.sort(function(a,b) {
  return moment(b, 'DD/MM/YYYY').valueOf() - moment(a, 'DD/MM/YYYY').valueOf();
})
share|improve this answer
    
My date format is not like that :P –  Joe Mar 25 at 15:28
    
what format.... –  wayne Mar 25 at 15:29
    
in thsi format : dd/mm/yyyy –  Joe Mar 25 at 15:29
    
There is no method of sort for objects, I am not working with arrays here :/ –  Joe Mar 25 at 17:59

First you'll want to write/get a date parser. Using Javascript's native Date object is unreliable for parsing raw strings.

Then you'll want to use Array.prototype.sort():

function parseDate(input) {
    var parts = input.split('/');
    return new Date(parts[2], parts[1]-1, parts[0]);
}

function sortAsc(a,b)
    { return parseDate(a.date) > parseDate(b.date); }

function sortDesc(a,b)
    { return parseDate(a.date) < parseDate(b.date); }

list.sort(sortAsc);
share|improve this answer

Here's a working example, the sorted table will contain ISO format dates

var dates = ["12/05/2012", "09/06/2011","09/11/2012"]
var sorted=[];
for(var i=0, i= dates.length;i++){
  var p = dates[i].split(/\D+/g);
  sorted[i]= new Date(p[2],p[1],p[0]);
}

alert(sorted.sort(function(a,b){return b-a}).join("\n"));

To get the same input format you can use this function:

function formatDate(d)
{
    date = new Date(d)
    var dd = date.getDate(); 
    var mm = date.getMonth()+1;
    var yyyy = date.getFullYear(); 
    if(dd<10){dd='0'+dd} 
    if(mm<10){mm='0'+mm};
    return d = dd+'/'+mm+'/'+yyyy
}
sorted.sort(function(a,b){return b-a})
formatSorted = []
for(var i=0; i<sorted.length; i++)
{
    formatSorted.push(formatDate(sorted[i]))
 }

alert(formatSorted.join("\n"));
share|improve this answer
    
This is an example of an array not an object? Nice answer though –  Joe Mar 25 at 18:03
    
Right, you have to parse your Json then loop over keys/values instead of array values. Sorry, thought the real difficulty was to sort with non-iso string dates –  radia Mar 25 at 19:16

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.