如何在 d3.json 命令中使用 d3.min 和 d3.max [英] How to use d3.min and d3.max within a d3.json command

查看:22
本文介绍了如何在 d3.json 命令中使用 d3.min 和 d3.max的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 d3 和 Javascript 的新手.我已经使用了 choropleth 示例,但现在想进行一些更详细的更改.其中之一是找到我用作输入的 JSON 的最大值和最小值.

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.

我的问题很简单,因为console.log(data)命令将对象下面的代码片段正确输出到控制台,但是整个对象也为min和max语句输出,而不仅仅是输出最小值和最大值.

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

这是 JSON 对象的片段:

Here is a snippet of the JSON object:

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

我想要的只是理解为什么 d3.min([data]) 和 d3.max([data]) 导致整个对象输出到控制台而不是最小和最大数字数据对象.

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.

提前致谢.

推荐答案

d3.min()d3.max() 函数对数组进行操作,而不是对对象.您似乎试图通过将 data 对象包装在一个数组中来解决这个问题(例如 d3.max([data])),但所有这一切实际上都是在说给我一个具有一个值(数据对象)的数组的最大值."由于数组中只有一个值,因此返回该值.

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.

如果你只想要对象中的最大值/最小值,你可以使用d3.values()函数将数据中的所有值提取为一个数组,然后取最大值在该数组中:

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

如果您也想知道密钥,您可能需要使用 d3.entries() 创建一个 { key, value } 对象数组,然后对它们进行排序并取顶部:

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 }

这篇关于如何在 d3.json 命令中使用 d3.min 和 d3.max的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆