1

I am plotting a d3 graph in which my data is coming from json and on x axis I am having dates but those dates are not coming in ascending order means those dates are not sorted. I have used the sort function but its not working because even after applying this sort function I am not getting sorted dates. Here is my snippet where I used sort function

if (filterByDates) {
   selectDate = true;
   tempData = fliterdata;
   console.log("before date fliter data", tempData);
   var date1 = new Date(document.getElementById('field1').value);
   var date2 = new Date(document.getElementById('field2').value);

   tempData = tempData.filter(function(d) {
       console.log(date1, date2);
       //  alert(date1);
       return d.date >= date1 && d.date <= date2;


   });
   console.log("After date fliter data", tempData);
}


xScale.domain(tempData.map(function(d) {
    return d.date;
}).sort(function(a, b) {
    return a > b;
}));
angelcool.net
  • 2,505
  • 1
  • 24
  • 26

1 Answers1

1

Your sort function on dates is incorrect, see https://stackoverflow.com/a/10124053/1071630 for a complete answer but the simplest comparison function would be

xScale.domain(
    tempData.map(function(d) {
        return d.date;
    }).sort(function(a, b) {
        return a - b;
    })
);

And a demo

var objs = [
    {date: new Date('2016-01-01T00:00:00')}, 
    {date: new Date('2014-01-01T00:00:00')}, 
];
 
var dates = objs.map(function(d) {
    return d.date;
}).sort(function(a, b) {
    return a - b;
});
    
var scale = d3.time.scale();
scale.domain(dates);

console.log('2015-01-01T00:00:00' +' ---> ' + scale(new Date('2015-01-01T00:00:00')));
console.log('2014-07-01T00:00:00' +' ---> ' + scale(new Date('2014-07-01T00:00:00')));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Community
  • 1
  • 1
nikoshr
  • 32,926
  • 33
  • 91
  • 105