I\'m new to d3 and Javascript. I have played around with the choropleth example but would like to now make some more detailed changes. One of which is to find the max and mi
I'm new to d3 and JavaScript as well but I found a workaround to find the min and max of three lines with objects, using d3.extent
and .concat
:
y.domain(
d3.extent(
d3.extent(data, function(d) {
return d.line1; })
.concat(d3.extent(data, function(d) {
return d.line2; })
.concat(d3.extent(data, function(d) {
return d.line3; })
))
));
The d3.min()
and d3.max()
functions operate on arrays, not on objects. You seem to be trying to address this by wrapping the data
object in an array (e.g. d3.max([data])
) but all this is really doing is saying "Give me the max value of an array with one value (the data object)." As there's only one value in the array, that value is returned.
If you just want the max/min value in the object, you can use the d3.values()
function to extract all the values in the data as an array, then take the max value in that array:
var max = d3.max(d3.values(data));
// 32710
If you want to know the key as well, you might need to use d3.entries()
to create an array of { key, value }
objects, then sort them and take the top:
// create an array of key, value objects
var max = d3.entries(data)
// sort by value descending
.sort(function(a, b) { return d3.descending(a.value, b.value); })
// take the first option
[0];
// { key: "01", value: 32710 }
If your data is an array, your original code will work, if you get rid of the brackets around data:
var data = [32710,20280,18002];
console.log(data);
console.log(d3.min(data));
console.log(d3.max(data));
If you need to identify the array values with the keys "01","02", "03", create an array of objects, and operate on the values to get min/max:
//data as key/value pairs
var data = [
{key: "01", value: 32710},
{key: "02", value: 20280},
{key: "03", value: 18002}
];
console.log(data);
console.log(d3.min(data, function(d) { return d.value; }));
console.log(d3.max(data, function(d) { return d.value; }));
// AND IF YOU WANT THE min/max of the KEYS:
console.log(d3.min(data, function(d) { return d.key; }));
console.log(d3.max(data, function(d) { return d.key; }));