我怎么在这里可以访问阵列总和? [英] How do I access the array sum here?

查看:79
本文介绍了我怎么在这里可以访问阵列总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据集,看起来大致是这样的:

I have a data set that looks roughly like this:

var dataset = [
  // apples
  [{"x": 1, "y": 5 }, { "x": 2, "y": 4 }, { "x": 3, "y": 2 }, { "x": 4, "y": 7 }, { "x": 5, "y": 23 }],
  // oranges
  [{ "x": 1, "y": 10 }, { "x": 2, "y": 12 }, { "x": 3, "y": 19 }, { "x": 4, "y": 23 }, { "x": 5, "y": 17 }],
  // grapes
  [{ "x": 1, "y": 22 }, { "x": 2, "y": 28 }, { "x": 3, "y": 32 }, { "x": 4, "y": 35 }, { "x": 5, "y": 43 }]
];

和我需要知道Y值可能达到的最高金额(恰好是最后一个系列中的 - 23 + 17 + 43 ) - 我认为我需要做的就是首先使用数组地图找的款项,然后把这些资金的最大。

And I need to know the highest possible sum of Y values (it happens to be the last one in the series -- 23 + 17 + 43) -- I think that what I need to do is first use an array map to find the sums, and then take the max of those sums.

我想我可以用的console.log(d3.max(d3.map(d3.sum(数据))))做到这一点; ,但我看到了什么控制台只是未定义 - 我的语法显然是错误的。

I thought I could do this with console.log(d3.max(d3.map(d3.sum(dataset)))); but what I see in the console is just undefined -- my syntax is clearly wrong.

我也试过这个,这是接近:

I also tried this, which is close:

dataset.map(function (a) {
  return d3.sum(a.map(function (d) { return d.y; }));
})

这给了我每个系列的总和(数组[41,81,160] )用的最多 160 ,而不是第一个项目的总和,其次是第二个项目(数组[37,44,53,65,83] ) - 我在寻找在latter--最大应 83

Which gives me the sum of each series (Array [ 41, 81, 160 ]) with a max of 160, not the sum of the first items, followed by the second items (Array [ 37, 44, 53, 65, 83]) -- I'm looking for the latter-- the max should be 83.

推荐答案

d3.zip() 就派上用场了这里,因为你是基于数组的索引操作数据。

d3.zip() comes in handy here, since you're manipulating data based on array index.

https://jsfiddle.net/guanzo/o8voyydx/2/

var result = dataset.map(d=>d.map(d=>d.y))
result = d3.zip.apply(undefined,result)
result = d3.max(result.map(d=>d3.sum(d)))
console.log(result )//83

这篇关于我怎么在这里可以访问阵列总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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