【问题标题】:Sum of multiple array elements and put this sum in table by index (x,y)多个数组元素的总和,并按索引 (x,y) 将此总和放入表中
【发布时间】:2018-10-22 17:16:00
【问题描述】:

我有以下数据(由 ajax 加载):

[
  {
    "x":     [1, 1, 2, 2, 2, 3, 3, 3, 4, 5],
    "y":     [3, 5, 4, 2, 5, 3, 4, 5, 1, 5],
    "Value": [18, 15, 11, 12, 9, 2, 33, 12, 2, 4],
  },
  {
    "x":     [1, 1, 2, 2, 2, 3, 3, 3, 4, 5],
    "y":     [3, 5, 4, 2, 5, 3, 4, 5, 1, 5],
    "Value": [16, 15, 11, 12, 9, 2, 33, 12, 2, 4],
  },
  {
    "x":     [1, 1, 2, 2, 2, 3, 3, 3, 4, 5],
    "y":     [3, 5, 4, 2, 5, 3, 4, 5, 1, 5],
    "Value": [14, 15, 11, 12, 9, 2, 33, 12, 2, 4],
  }
]

我有a 5x5 table

如何计算“值”的每个多个元素的总和并将其放入右索引表中?

我现在的 js 代码:

function risk(data) {
    let sum = 0;

    for (i = 0; i < data.length; i++) {
      let b = data[i].Value;
      console.log(b); // (10) [18, 15, 11, 12, 9, 2, 33, 12, 2, 4]
                      // (10) [16, 15, 11, 12, 9, 2, 33, 12, 2, 4]
                      // (10) [14, 15, 11, 12, 9, 2, 33, 12, 2, 4]
    }
}

最终的结果一定是这样的:

【问题讨论】:

  • 请为结果添加所需的数据结构。
  • @ninaScholz 你的意思是html中的表格吗?
  • 那么你尝试了什么?

标签: javascript arrays count sum tabular


【解决方案1】:

您可以使用一个对象来收集值。为了将结果返回到表中,您可以迭代坐标并获取一个值。

var data = [{ x: [1, 1, 2, 2, 2, 3, 3, 3, 4, 5], y: [3, 5, 4, 2, 5, 3, 4, 5, 1, 5], Value: [18, 15, 11, 12, 9, 2, 33, 12, 2, 4] }, { x: [1, 1, 2, 2, 2, 3, 3, 3, 4, 5], y: [3, 5, 4, 2, 5, 3, 4, 5, 1, 5], Value: [16, 15, 11, 12, 9, 2, 33, 12, 2, 4] }, { x: [1, 1, 2, 2, 2, 3, 3, 3, 4, 5], y: [3, 5, 4, 2, 5, 3, 4, 5, 1, 5], Value: [14, 15, 11, 12, 9, 2, 33, 12, 2, 4] }],
    sum = data.reduce((r, {x, y, Value}) => 
        (x.forEach((x, i) => {
        r[x] = r[x] || {};
        r[x][y[i]] = (r[x][y[i]] || 0) + Value[i];
    }), r), {});
    
console.log(sum);

【讨论】:

  • 哦,看来我正在寻找的结果..现在需要找出如何将我需要的精确数据放在正确的表格行和列中..谢谢!!!!跨度>
  • 你知道如何在新对象中计算“零”值吗?
  • 您可以迭代 xy 并使用默认值访问该值,例如 (sum[x] || {})[y] || 0
【解决方案2】:

您可以使用reduce 来构建您的“结果”矩阵,在您遍历原始数据中的所有元素时,将“值”添加到矩阵中相应的xy 坐标中。

const data = [
  {
    "x":     [1, 1, 2, 2, 2, 3, 3, 3, 4, 5],
    "y":     [3, 5, 4, 2, 5, 3, 4, 5, 1, 5],
    "Value": [18, 15, 11, 12, 9, 2, 33, 12, 2, 4],
  },
  {
    "x":     [1, 1, 2, 2, 2, 3, 3, 3, 4, 5],
    "y":     [3, 5, 4, 2, 5, 3, 4, 5, 1, 5],
    "Value": [16, 15, 11, 12, 9, 2, 33, 12, 2, 4],
  },
  {
    "x":     [1, 1, 2, 2, 2, 3, 3, 3, 4, 5],
    "y":     [3, 5, 4, 2, 5, 3, 4, 5, 1, 5],
    "Value": [14, 15, 11, 12, 9, 2, 33, 12, 2, 4],
  }
];

const res = new Array(5).fill(0).map(n => new Array(5).fill(0));
data.reduce((acc, curr) => {
  curr.Value.forEach((v, i) => acc[curr.x[i] - 1][curr.y[i] - 1] += v);
  return res;
}, res);

console.log(res);

【讨论】:

    猜你喜欢
    • 2019-04-21
    • 2016-07-22
    • 2019-05-12
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多