Trel
Trel

Reputation: 145

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

The json is coming from a couchdb database

I can get the lines to draw, but they are a mess:

enter image description here

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.

Upvotes: 14

Views: 10698

Answers (1)

Oleg
Oleg

Reputation: 9359

Why don't you just sort your data after your forEach where you populate date properties? 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.

Upvotes: 18

Related Questions