[英]Get the object with the max value with D3
I have an array of objects from which I can easily get a max value like this: 我有一个对象数组,可以从中轻松获得最大值,如下所示:
var maxValue = d3.max(data, function (d, i) {
return d.value
});
Now, how can I get not the max value, but the object which contains this value? 现在,如何获取最大值而不是包含该值的对象? Is there a D3-specific way to do this?
有D3特定的方式来做到这一点吗?
No need for D3 here, the Javascript built-in .sort()
is enough: 此处无需D3,内置的Javascript
.sort()
就足够了:
data.sort(function(a, b) { return b.value - a.value; });
After this, data
will be in descending order. 此后,
data
将按降序排列。 That is, data[0]
is the element with the highest .value
. 也就是说,
data[0]
是具有最大.value
的元素。
A crude implementation: 粗略的实现:
(function()
{
d3.each = function(array, fn, context)
{
for(var i = 0, len = array.length; i < len; i++)
{
fn.call(context || this, array[i], i);
}
}
})();
var data = [{ 'value' : 1 }, { 'value' : 6 }, { 'value' : 100 }, { 'value' : 56 }, { 'value' : 21 }];
var max = null;
d3.each(data, function(d, i)
{
if(!max || d.value > max.value)
{
max = d;
}
});
console.log(max)
http://jsfiddle.net/xhVn4/ http://jsfiddle.net/xhVn4/
You also get a fancy (not really :) ) new d3 helper function (couldn't fnd it in the D3 API) 您还会得到新奇的(不是真的:))新的d3辅助函数(无法在D3 API中找到它)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.