如何在javascript中对日期数组进行排序

时间:2015-08-14 07:08:39

标签: javascript arrays sorting

我有以下数组日期,我想按加入顺序对其进行排序。我试过但没有得到积极的结果。

var arr = [ [ '02/13/2015', 0.096 ],
  [ '11/15/2013', 0.189 ],
  [ '05/15/2014', 0.11 ],
  [ '12/13/2013', 0.1285 ],
  [ '01/15/2013', 0.12 ],
  [ '01/15/2014', 0.11 ],
  [ '02/14/2014', 0.11 ],
  [ '03/14/2014', 0.11 ],
  [ '01/15/2015', 0.096 ],
  [ '07/15/2015', 0.096 ],
  [ '04/15/2013', 0.12 ],
  [ '04/15/2014', 0.11 ],
  [ '05/15/2013', 0.12 ],
  [ '06/14/2013', 0.12 ],
  [ '06/16/2014', 0.11 ],
  [ '07/15/2013', 0.12 ],
  [ '07/15/2014', 0.11 ],
  [ '03/16/2015', 0.096 ]]

我的代码

arr.sort(function(a,b){
  return new Date(a[0][0]) - new Date(b[0][0]);
});

3 个答案:

答案 0 :(得分:7)

您正在使用日期字符串中的第一个字符,将它们转换为Date个实例并将其用于比较。

但是,您应该按原样使用Date字符串,将它们转换为Date个实例并进行比较。

arr.sort(function (a, b) {
  return new Date(a[0]) - new Date(b[0]);
});

<强>输出

[ [ '01/15/2013', 0.12 ],
  [ '04/15/2013', 0.12 ],
  [ '05/15/2013', 0.12 ],
  [ '06/14/2013', 0.12 ],
  [ '07/15/2013', 0.12 ],
  [ '11/15/2013', 0.189 ],
  [ '12/13/2013', 0.1285 ],
  [ '01/15/2014', 0.11 ],
  [ '02/14/2014', 0.11 ],
  [ '03/14/2014', 0.11 ],
  [ '04/15/2014', 0.11 ],
  [ '05/15/2014', 0.11 ],
  [ '06/16/2014', 0.11 ],
  [ '07/15/2014', 0.11 ],
  [ '01/15/2015', 0.096 ],
  [ '02/13/2015', 0.096 ],
  [ '03/16/2015', 0.096 ],
  [ '07/15/2015', 0.096 ] ]

答案 1 :(得分:1)

来自MDN Sorting with map的大力启发。这对于更大的数据集非常重要。

var arr = [
    ['02/13/2015', 0.096],
    ['11/15/2013', 0.189],
    ['05/15/2014', 0.11],
    ['12/13/2013', 0.1285],
    ['01/15/2013', 0.12],
    ['01/15/2014', 0.11],
    ['02/14/2014', 0.11],
    ['03/14/2014', 0.11],
    ['01/15/2015', 0.096],
    ['07/15/2015', 0.096],
    ['04/15/2013', 0.12],
    ['04/15/2014', 0.11],
    ['05/15/2013', 0.12],
    ['06/14/2013', 0.12],
    ['06/16/2014', 0.11],
    ['07/15/2013', 0.12],
    ['07/15/2014', 0.11],
    ['03/16/2015', 0.096]
];

// temporary array holds objects with position and sort-value
var mapped = arr.map(function (el, i) {
    var d = el[0].split('/');
    return { index: i, value: new Date(d[2], d[0] - 1, d[1]) };
})

// sorting the mapped array containing the reduced values
mapped.sort(function (a, b) {
    return +(a.value > b.value) || +(a.value === b.value) - 1;
});

// container for the resulting order
var result = mapped.map(function (el) {
    return arr[el.index];
});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

答案 2 :(得分:0)

如果你想要的只是按日期排序,我认为这段代码会有所帮助:

arr.sort(function(a,b){return new Date(a[0]) - new Date(b[0]);});