如何在有空白时对日期数据进行排序

时间:2016-12-24 23:31:49

标签: javascript sorting

我写了这段代码来对日期字段fdate进行升序或降序排序但是我得到了这种空白值,我需要的是如果我按升序排序或如何放置所有空白记录当我按降序排序时,这些空白记录在最后?

var dataset = [{
  "field1": "dfg34r",
  "field2": "32.24"
}, {
  "field1": "d3f32dg",
  "field2": "32.52",
  "fdate": "3/2/2015"
}, {
  "field1": "fdbhjjts",
  "fdate": "7/4/2015"
}, {
  "field1": "dfg4r",
  "field2": "2.24"
}, {
  "field1": "fgsdfwe",
  "fdate": "3/1/2015"
}];

dataset.sort(function(a, b) {
      var x = new Date(a.fdate);
      var y = new Date(b.fdate);
      return x.valueOf() - y.valueOf();
    });

document.getElementById("demo").innerHTML = JSON.stringify(dataset);
<p id="demo"></p>

1 个答案:

答案 0 :(得分:1)

更通用的解决方案是检查属性是否缺失,并返回1-1以确定排序顺序。无论数据类型如何,这都有效。

我添加了factor选项,您可以更改该选项以确定升序/降序。

var dataset = [{"field1":"dfg34r","field2":"32.24"},{"field1":"d3f32dg","field2":"32.52","fdate":"3/2/2015"},{"field1":"fdbhjjts","fdate":"7/4/2015"},{"field1":"dfg4r","field2":"2.24"},{"field1":"fgsdfwe","fdate":"3/1/2015"}];

var factor = 1; // change to -1 for descending

dataset.sort(function(a, b) {
  // if prop a doesn't exist
  if (!a.fdate) {
    return factor * -1;
  }

  // if prop b doesn't exist
  if (!b.fdate) {
    return factor * 1;
  }

  return factor * (new Date(a.fdate) - new Date(b.fdate));
});

console.log(dataset);

原始解决方案

如果fdate不存在,请改用0new Date(0)是unix时间的第一个日期 - 1970年1月1日星期四02:00:00 GMT + 0200(东欧标准时间)。

var dataset = [{"field1":"dfg34r","field2":"32.24"},{"field1":"d3f32dg","field2":"32.52","fdate":"3/2/2015"},{"field1":"fdbhjjts","fdate":"7/4/2015"},{"field1":"dfg4r","field2":"2.24"},{"field1":"fgsdfwe","fdate":"3/1/2015"}];

dataset.sort(function(a, b) {
  var x = new Date(a.fdate || 0);
  var y = new Date(b.fdate || 0);
  return x.valueOf() - y.valueOf();
});

console.log(dataset);