【问题标题】:A better way to group a multidimensional array对多维数组进行分组的更好方法
【发布时间】:2016-07-24 14:27:12
【问题描述】:

下面的数据代表一个[股票代码、金额、单一价值]

var data = [
  ['A', 140, 82.4],
  ['B', 100, 55.5],
  ['A', 30, 77.2],
  ['B', 200, 60.1]
];

如何按股票代码分组,并使用 JavaScript 的 Map、Reduce 和 Filter 计算平均价格和总价值,在一个新的矩阵中,如 [股票代码、金额、平均价格、总价值]:

var newData = [
  ['A', 170, 81.482, 13852], 
  ['B', 300, 58.566, 17570]]
];

这是我到目前为止所尝试的。就最短、优雅的代码而言,有一种方法可以更有效地处理这段代码吗?

var newData = data.map(function(item) {
  return data.filter(function(itemFilter) {
    return itemFilter[0] == item[0];
  })
  .reduce(function(array, item) {
    array[0] = item[0];
    array[1] += item[1];
    array[3] += (item[1] * item[2]);
    array[2] = array[3] / array[1];
    return array;
  }, ['', 0, 0, 0]);
})
//Remove duplicate items
.filter(function(item, index, inputArray) {
  return inputArray.map(function(item) {
    return item[0];
  }).indexOf(item[0]) == index;
});

【问题讨论】:

  • 使用一个以股票代码为键的对象。然后您可以轻松收集与股票相关的所有值并计算总数和平均值。
  • 为什么要投反对票?这是重现问题的代码的最小版本。数据来自电子表格,有几十列。我想使用 map/reduce 以获得更简化和优化的代码,但我目前阅读的示例仅处理简单的数组。

标签: javascript multidimensional-array reduce


【解决方案1】:

您可以使用临时对象this 来引用结果数组newData,并添加位置并计算数组的平均值,其中第一项作为键this[a[0]]

var data = [['A', 140, 82.4], ['B', 100, 55.5], ['A', 30, 77.2], ['B', 200, 60.1]],
    newData = [];

data.forEach(function (a) {
    var product = a[1] * a[2];
    if (!this[a[0]]) {
        this[a[0]] = [a[0], 0, 0, 0];
        newData.push(this[a[0]]);
    }
    this[a[0]][1] += a[1];
    this[a[0]][3] += product;
    this[a[0]][2] = this[a[0]][3] / this[a[0]][1];
}, {});

document.write('<pre>' + JSON.stringify(newData, 0, 4) + '</pre>');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多