Skip to content Skip to sidebar Skip to footer

Sort Json Array By Date Key

I have a json array and I am trying to sort it by date before I append it. The array looks as such: result = []; result.push( {id: 'ID', result: {url: 'test', date: '15 May 2013,

Solution 1:

function comp(a, b) {
    return new Date(a.result.date).getTime() - new Date(b.result.date).getTime();
}

your_array.sort(comp);

Just to extend @Karthikr's comment.

var result = [];

result.push({
  id: 'ID',
  result: {
    url: 'test',
    date: '15 May 2013, 6:40 pm'
  }
}, {
  id: 'ID',
  result: {
    url: 'test',
    date: '20 Dec 2012, 8:00 am'
  }
}, {
  id: 'ID',
  result: {
    url: 'test',
    date: '29 Jun 2012, 5:47 pm'
  }
});

functioncomp(a, b) {
  returnnewDate(a.result.date).getTime() - newDate(b.result.date).getTime();
}

result.sort(comp);

$('body').append(JSON.stringify(result));
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Post a Comment for "Sort Json Array By Date Key"