wink
wink

Reputation: 57

Sort Element in Array of Array Javascript

I wish to sort the arrays by the time (which is the 3rd element). However, when I print out the result, the sequence of the array seems to have no difference.

Can I know what's the error? Thank you!

const events =[
  [ 1, '1230000003', '09:00:00' ],
  [ -1, '1230000003', '14:00:00' ],
  [ -1, '1110000002', '12:30:00' ],
  [ 1, '1110000002', '14:00:00' ],
  [ -1, '1110000007', '08:30:00' ],
  [ 1, '1110000007', '11:00:00' ],
  [ -1, '1110000008', '09:00:00' ],
  [ 1, '1110000008', '12:00:00' ]
]

This is my code:

 events.sort((a, b) => a[0][2] - b[0][2]);
 console.log("sorted start time",events);

Upvotes: 2

Views: 75

Answers (3)

GirkovArpa
GirkovArpa

Reputation: 4912

Change this;

 events.sort((a, b) => a[0][2] - b[0][2]);

To this:

events.sort((a, b) => a[2] > b[2] ? 1 : -1);

Result:

[
  [-1, "1110000007", "08:30:00"],
  [-1, "1110000008", "09:00:00"],
  [1, "1230000003", "09:00:00"],
  [1, "1110000007", "11:00:00"],
  [1, "1110000008", "12:00:00"],
  [-1, "1110000002", "12:30:00"],
  [1, "1110000002", "14:00:00"],
  [-1, "1230000003", "14:00:00"]
]

Upvotes: 1

Sven.hig
Sven.hig

Reputation: 4519

You could use localCompare

const events =[ [ 1, '1230000003', '09:00:00' ], [ -1, '1230000003', '14:00:00' ], [ -1, '1110000002', '12:30:00' ], [ 1, '1110000002', '14:00:00' ], [ -1, '1110000007', '08:30:00' ], [ 1, '1110000007', '11:00:00' ], [ -1, '1110000008', '09:00:00' ], [ 1, '1110000008', '12:00:00' ] ]
events.sort((a, b) => a[2].localeCompare(b[2]));
console.log("sorted start time",events);

Upvotes: 2

Harmandeep Singh Kalsi
Harmandeep Singh Kalsi

Reputation: 3345

Since it is date is string , you should use the sort function as

const events =[
  [ 1, '1230000003', '09:00:00' ],
  [ -1, '1230000003', '14:00:00' ],
  [ -1, '1110000002', '12:30:00' ],
  [ 1, '1110000002', '14:00:00' ],
  [ -1, '1110000007', '08:30:00' ],
  [ 1, '1110000007', '11:00:00' ],
  [ -1, '1110000008', '09:00:00' ],
  [ 1, '1110000008', '12:00:00' ]
]

events.sort((a, b) => a[2].localeCompare(b[2]));
console.log(events);

Upvotes: 2

Related Questions