javascript - 减少多维数组

标签 javascript arrays multidimensional-array mapreduce

我目前正在尝试映射和缩减函数以展平多维数组。
这是一个模拟示例数据集:

data: [
  {
    label: "Sort-01"
    data: [
      {
        label: "OCT-2017"
        weight: 2304
      },
      {
        label: "NOV-2017"
        weight: 1783
      }
    ]
  },
  {
    label: "Sort-02"
    data: [
      {
        label: "OCT-2017"
        weight: 4785
      },
      {
        label: "NOV-2017"
        weight: 102
      }
    ]
  },
 ......
]

我知道为了按排序编号进行 map-reduce,我可以使用:

data.map(sort => sort.data.reduce((a,b) => a.weight + b.weight));

但是,我想按月减少而不是排序数字。
我将不胜感激任何帮助。

谢谢,
周杰伦

最佳答案

使用 Array#map 获取 data 属性数组的数组,然后用 Array#concat 展平和 spread .使用 Array#reduce将值收集到 Map 中, 然后使用 Map#values ,以及转换回数组的扩展语法:

const array = [{"label":"Sort-01","data":[{"label":"OCT-2017","weight":2304},{"label":"NOV-2017","weight":1783}]},{"label":"Sort-02","data":[{"label":"OCT-2017","weight":4785},{"label":"NOV-2017","weight":102}]}];

const result = [... // spread the values iterator to an array
  [].concat(...array.map(({ data }) => data)) // map the array into an array of data arrays
  .reduce((m, { label, weight }) => {
    // take item if label exists in map, if not create new
    const item = m.get(label) || { label, weight: 0 };
    
    item.weight += weight; // add the weight
  
    return m.set(label, item); // set the item in the map
  }, new Map).values()] // get the values iterator

console.log(result);

这是一个无传播版本:

const array = [{"label":"Sort-01","data":[{"label":"OCT-2017","weight":2304},{"label":"NOV-2017","weight":1783}]},{"label":"Sort-02","data":[{"label":"OCT-2017","weight":4785},{"label":"NOV-2017","weight":102}]}];

const helper = Object.create(null);
const result = [].concat.apply([], array.map(({ data }) => data)) // map the array into an array of data arrays, and flatten by apply concat
  .reduce((r, { label, weight }) => {
    // if label is not in helper, add to helper, and push to r
    if(!helper[label]) {
      helper[label] = { label, weight: 0 };
      r.push(helper[label]);
    }
    
    helper[label].weight += weight; // add the weight to the object
  
    return r;
  }, []) // get the values iterator

console.log(result);

关于javascript - 减少多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46813206/

相关文章:

java - 使用位运算符 JAVA 交换 int[][] 数组中每行/列的顶部和底部 2 位

javascript - 在 ES6 中创建多维数组

Java:二维数组以列优先还是行优先顺序存储?

javascript - ECMAScript 中 Atomics 对象的实际用途是什么?

javascript - innerHtml 在 ie 中不适用于表格

c++ - 是否可以定义一个指向具有 "not"可变参数列表的函数的指针,例如 "bools"?

javascript - 过滤器可以在将元素返回到新数组之前对其进行操作吗?

java - Java中将字节数组转换为int数组,通过ByteBuffer到IntBuffer,不截断

javascript - 中止 POST XHR 可靠吗?

javascript - 将 Javascript onClick 事件添加到 HTML 复选框阻止了我 'unchecking' 复选框