Reputation: 927
I am using d3 and trying to compare dates in an array. I want to get the minimum and maximum of it.
The following is my data set.
var data = [{ "date": "2016.07.19", "close": 185697.89 }, { "date": "2016.07.20", "close": 185697.89 }, { "date": "2016.07.21", "close": 186601.1 }, { "date": "2016.07.22", "close": 187273.89 }, { "date": "2016.07.25", "close": 186807.74 }];
The following is the code segment I am having the issue with
max_x = 0, max_y = 0, min = 100;
for (i = 0; i < data.length; i++) {
max_y = Math.max(max_y, data[i].close);
max_x = Math.max(max_x, data[i].date);
min = Math.min(min, data[i].date);
}
When I printed the "min" variable, it printed "NaN".
This is affecting the rest of my code.
Can someone point out where I've gone wrong ? Is there any other way to do date comparison ?
Upvotes: 2
Views: 1262
Reputation: 46
You can put the properties date and close into two arrays separately,such as dateArr ["2016.07.19","2016.07.20","2016.07.21"],closeArr [185697.89,186601.1,187273.89], and sort them by asc,the first item in array is the minimum,and the last item is the maximum.
Upvotes: 0
Reputation: 102174
Your date
values are strings. You have to parse them:
var parse = d3.timeParse("%Y.%m.%d");
After that, you can retrieve the minimum with d3.min
, the maximum with d3.max
or both of them with d3.extent
.
Here is the demo:
var data = [{ "date": "2016.07.19", "close": 185697.89 }, { "date": "2016.07.20", "close": 185697.89 }, { "date": "2016.07.21", "close": 186601.1 }, { "date": "2016.07.22", "close": 187273.89 }, { "date": "2016.07.25", "close": 186807.74 }];
var parse = d3.timeParse("%Y.%m.%d");
var extent = d3.extent(data.map(function(d){ return parse(d.date)}))
console.log("Minimum: " + extent[0])
console.log("Maximum: " + extent[1])
<script src="https://d3js.org/d3.v4.min.js"></script>
Upvotes: 2