Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

d3.js - How to use d3.min and d3.max within a d3.json command

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 min of the JSON that I am using as input.

My question is simple, for the code snippet below the object is output correctly to the console for the console.log(data) command, however the entire object is also output for the min and max statements as well instead of just the min and the max.

d3.json("data/unemployment_by_state.json", function(data) {   
  console.log(data);
  console.log(d3.min([data]));
  console.log(d3.max([data]));
});

Here is a snippet of the JSON object:

{"01":32710,"02":20280,"03":18002}

All I would like some help with is understanding why the d3.min([data]) and d3.max([data]) are causing the entire object to be output to the console instead of the min and max number in the data object.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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; }));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...