如何使用JavaScript对2D数组进行排序?

时间:2018-07-04 08:08:39

标签: javascript arrays sorting

如何使用JavaScript对2D数组进行排序?

我有任何这样的数组:

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']]

我想按第二个元素(arr [1])排序 我该怎么办?

我以前很累:

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

这是我的控制台结果:

["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"]

但这是我的预期结果:

[["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']

2 个答案:

答案 0 :(得分:0)

因为arr[1]是一个日期,所以您需要像这样使用new Date()进行比较:

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)

答案 1 :(得分:0)

有关更多信息,请参见Array.prototype.sort()

// 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)