Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort array of objects by time string value?

I have an array of objects like so :

var example = [{
  "description": "aaa",
  "time": "12:15pm"
}, {
  "description": "bbb",
  "time": "10:10am"
}, {
  "description": "ccc",
  "time": "4:00pm"
}, {
  "description": "ddd",
  "time": "6:15pm"
}, {
  "description": "eee",
  "time": "1:10am"
}, {
  "description": "fff",
  "time": "5:00pm"
} ];

I want to sort by the time value.

I have tried to apply this solution which was intended for an array of string values:

example.sort(function (a, b) {
  return new Date('1970/01/01 ' + a.time) - new Date('1970/01/01 ' + b.time);
});

console.log(example);

I've also been referring to the Mozilla Array.prototype.sort() documentation and tried the following which didn't seem to work:

example.sort(function(a, b) {
  if (new Date(a.time) > new Date(b.time)) {
    return 1;
  }
  if (new Date(a.time) < new Date(b.time)) {
    return -1;
  }
  // a must be equal to b
  return 0;
});

console.log(example);
like image 808
user1063287 Avatar asked Jun 08 '16 12:06

user1063287


1 Answers

The date string that you are generating is not valid so it will always returns current date and time. So generate valid date string(eg : '1970/01/01 9:34:48 AM') then parse and return the difference. Here String#slice() method can be used to generate the valid date string.

var example = [{
  "description": "aaa",
  "time": "12:15pm"
}, {
  "description": "bbb",
  "time": "10:10am"
}, {
  "description": "ccc",
  "time": "4:00pm"
}, {
  "description": "ddd",
  "time": "6:15pm"
}, {
  "description": "eee",
  "time": "1:10am"
}, {
  "description": "fff",
  "time": "5:00pm"
}];

example.sort(function(a, b) {
  // get time time from string 
  // then get am or pm from string and append
  // both can be done using slice method
  return Date.parse('1970/01/01 ' + a.time.slice(0, -2) + ' ' + a.time.slice(-2)) - Date.parse('1970/01/01 ' + b.time.slice(0, -2) + ' ' + b.time.slice(-2))
});

console.log(example);
like image 93
Pranav C Balan Avatar answered Oct 06 '22 01:10

Pranav C Balan