如何使用D3.js在一个下拉列表中按照自然的方式安排日期

How to arrange dates in a drop-down list according their natural way using D3.js

本文关键字:自然 日期 方式安 下拉列表 一个 js D3 何使用      更新时间:2023-09-26

我有一个数据集,其中有一些日期。现在日期随机排列(三月-二月-一月):

var uniqueDates = ["2016-03-01", "2016-01-01", "2016-02-01"];

我需要将这些日期按自然顺序(1月- 2月- 3月)放入下拉列表中。现在我使用下面的代码:

d3.select("select#dateSelector")
  .selectAll("option")
  .data(uniqueDates)
  .enter()
  .append("option")
  .text(function(d) {
    return formatRU(new Date(d));
  })
  .attr("value", function(d) {
    return d;
  })
  .property("selected", function(d) {
    return i == uniqueDates.length - 1;
  });

我怎样才能在我的下拉列表中得到正确的顺序呢?

<select id="dateSelector">
  <option value="2016-01-01">Январь 2016</option>
  <option value="2016-02-01">Февраль 2016</option>
  <option value="2016-03-01">Март 2016</option>
</select>

对日期的字符串表示形式进行排序,将它们实际转换为Date对象:

uniqueDates.sort(function(a, b){
    return d3.ascending(new Date(a), new Date(b));
});