简体   繁体   English

日期使用d3.js排序

[英]Date Sorting with d3.js

Disclaimer: I have no idea what I'm doing. 免责声明:我不知道我在做什么。 Seriously, I love data viz and thought that doing it myself would be a great way to learn to program and use databases and make web apps like a cool guy. 说真的,我喜欢数据,并认为自己做这将是学习编程和使用数据库以及使网络应用程序像一个很酷的家伙的好方法。 I've been at this searching for answer for the last day, and all the examples I could find I couldn't make work with my code. 我一直在寻找最后一天的答案,而我能找到的所有例子都无法使用我的代码。

Here is a paste bin of the full code and data I'm using. 这是我正在使用的完整代码和数据的粘贴框。 It's the sample line chart found on the d3.js github with my data filled in. http://pastebin.com/7aW6wegd 这是对我的数据填入d3.js github上发现了样品线图。 http://pastebin.com/7aW6wegd

The json is coming from a couchdb database json来自couchdb数据库

I can get the lines to draw, but they are a mess: 我可以得到画线,但它们是一团糟:

在此输入图像描述

I THINK this is caused by the dates not sorting properly, since in console they are listed out of order. 我认为这是由于日期没有正确排序造成的,因为在控制台中它们是按顺序列出的。 I can't figure out how to get the date's to sort properly. 我无法弄清楚如何正确排序日期。 Using d3.time.format throws errors (you can actually see it in the code I've taken from the sample line chart, they use it to parse the dates. Using it with my data throws an error, even after I try to turn the timestamps to dates) and I can't seem to figure out how to get the dates to sort in couchdb either. 使用d3.time.format会抛出错误(你可以在我从代码行图中获取的代码中实际看到它,它们使用它来解析日期。使用它和我的数据会引发错误,即使在我尝试转向之后也是如此时间戳到日期)我似乎无法弄清楚如何在couchdb中排序日期。

Why don't you just sort your data after your forEach where you populate date properties? 为什么不在填充date属性的forEach之后对数据进行排序? Here's a very basic implementation of a sorter of an array of objects: 这是一个对象数组的分类器的一个非常基本的实现:

var data = [
         {date: new Date(2000)},
         {date: new Date(1000)}
    ];

function sortByDateAscending(a, b) {
    // Dates will be cast to numbers automagically:
    return a.date - b.date;
}

data = data.sort(sortByDateAscending);

There's a nice documentation for the Array.prototype.sort . 有一个很好的Array.prototype.sort 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM