0

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

Joe
  • 267
  • 1
  • 6
  • 17

3 Answers3

0

include moment.js

fileListObj.sort(function(a,b) {
  return moment(b, 'DD/MM/YYYY').valueOf() - moment(a, 'DD/MM/YYYY').valueOf();
})
wayne
  • 3,410
  • 19
  • 11
0

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);
Community
  • 1
  • 1
Dissident Rage
  • 2,610
  • 1
  • 27
  • 33
0

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"));
radia
  • 1,456
  • 1
  • 13
  • 18
  • This is an example of an array not an object? Nice answer though – Joe Mar 25 '14 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 '14 at 19:16