Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 621
Trel Avatar asked Sep 26 '14 19:09

Trel


People also ask

How do I sort data in D3 JS?

sort() function in D3. js is used to sort the children at each level of the given hierarchical data. The comparator function can be used to define the basis on which the sorting would be done.

How do I sort a date in TypeScript?

To sort an array of objects by date in TypeScript: Call the sort() method on the array, passing it a function. The function will be called with 2 objects from the array. Subtract the timestamp of the date in the second object from the timestamp of the date in the first.


1 Answers

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.

like image 126
Oleg Avatar answered Sep 22 '22 02:09

Oleg