-2

How can I sort 2D array with JavaScript?

I have any array like this:

arr = [["123", "2017-07-11 15:00", '1'],
      ["124","2017-07-04 16:00", '1'],
      ["125","2017-07-05 12:00", '1'],
      ["126","2017-07-04 21:00", '1'],
      ["127","2017-07-03 02:00", '1'],
      ["128","2017-07-05 11:00", '1'],
      ["129","2017-07-05 14:00", '1']]

And I want to sort by the second element (arr[1]) How Can I do that?

I tired this before:

let b = arr.map(x=> x[1]).sort();
console.log(b);

And this is my console result:

["2017-07-03 02:00", 
"2017-07-04 16:00", 
"2017-07-04 21:00", 
"2017-07-05 11:00", 
"2017-07-05 12:00", 
"2017-07-05 14:00", 
"2017-07-11 15:00"]

But this is my expected result:

[["127", "2017-07-03 02:00", '1'], 
["124","2017-07-04 16:00", '1'], 
["126","2017-07-04 21:00", '1'], 
["128","2017-07-05 11:00", '1'], 
["125","2017-07-05 12:00", '1'], 
["129","2017-07-05 14:00", '1'], 
["123","2017-07-11 15:00", '1']
Lynn
  • 127
  • 2
  • 10

2 Answers2

0

since arr[1] is a date you need to compare them using new Date() like :

const arr = [
  ["123", "2017-07-11 15:00", '1'],
  ["124", "2017-07-04 16:00", '1'],
  ["125", "2017-07-05 12:00", '1'],
  ["126", "2017-07-04 21:00", '1'],
  ["127", "2017-07-03 02:00", '1'],
  ["128", "2017-07-05 11:00", '1'],
  ["129", "2017-07-05 14:00", '1']
]

const result = arr.sort((a, b) => {
  return new Date(a[1]) - new Date(b[1])
})

console.log(result)
Taki
  • 15,354
  • 3
  • 20
  • 39
0

See Array.prototype.sort() for more info.

// Input.
const input = [["123", "2017-07-11 15:00", '1'],["124","2017-07-04 16:00", '1'],["125","2017-07-05 12:00", '1'],["126","2017-07-04 21:00", '1'],["127","2017-07-03 02:00", '1'],["128","2017-07-05 11:00", '1'],["129","2017-07-05 14:00", '1']]

// Sort.
const sort = x => x.sort((A, B) => {
  const dateA = new Date(A[1])
  const dateB = new Date(B[1])
  return dateA - dateB
})

// Output.
const output = sort(input)

// Proof.
console.log(output)
Arman Charan
  • 4,717
  • 2
  • 18
  • 26
  • If it's not a date formate, how can I sort my array? – Lynn Jul 04 '18 at 08:32
  • `Array.prototype.sort()` expects a `number`. So for `numbers`: the same strategy applies. For `strings`: `numbers` must be passed manually based on `> / < / ==` comparison. There are examples of each in the documentation I linked @Lynn – Arman Charan Jul 04 '18 at 08:40