简体   繁体   English

JavaScript Map Reduce 函数

[英]JavaScript Map Reduce Function

I'm new to javascript and using JSON datasource trying to aggregate data to display correctly on webpage, and this dataset gets subsetted based on user activity.我是 javascript 新手,并使用 JSON 数据源尝试聚合数据以在网页上正确显示,并且此数据集根据用户活动进行子集化。 Some of these datasets can get to be 100s of records, so being fast is important.其中一些数据集可以达到 100 条记录,因此速度快很重要。

# here is my data
jsonData=
        {
        "data": [{
          "name": "13_WH1",
          "attributes": {
            "bv": 145
          },
          "vm": [
            4.0,
            8.0,
            6.0,
            6.0
          ]
        },
        {
          "name": "32_WH2",
          "attributes": {
            "bv": 155
          },
          "vm": [
            5.0,
            7.0,
            7.0,
            2.0
          ]
       }]
    }
function sumVm(data_set){
    data_set.map(function(series, index) {
      const total_vm = series.data.reduce(
        (accumulator, record) => accumulator + record.vm,
        0
      );
      console.log(total_vm)
      return total_vm

    })
};

When I call the function, here is my result (which is just repeating each record, not adding by position.当我调用该函数时,这是我的结果(只是重复每条记录,而不是按位置添加。

sumVm(jsonData)
// 04,8,6,65,7,7,2

The desired result i would want is:我想要的结果是:

// 9,15,13,8

Any suggestions would be very helpful, thank you任何建议都会非常有帮助,谢谢

Here is one way of doing it.这是一种方法。 Flat mapping and then using foreach to build a new array of values.平面映射,然后使用 foreach 构建一个新的值数组。

 let jsonData = [{ "foo": "bar", "data": [{ "name": "13_WH1", "attributes": { "bv": 145, }, "vm": [ 4.0, 8.0, 6.0, 6.0 ] }, { "name": "32_WH2", "attributes": { "bv": 155, }, "vm": [ 5.0, 7.0, 7.0, 2.0 ] } ] }] function sumVm(data_set) { let a = [] data_set.flatMap(e => e.data.map(d => d.vm)).forEach(e => e.forEach((f, i) => { if (!a[i]) a[i] = 0; a[i] = a[i] + f })) return a }; console.log(sumVm(jsonData)) // 9,15,13,8

Loop through the first item's vm property and use a nested loop to loop through all items and extract the vm property, then get the item at the index and add to a variable.循环遍历第一项的vm属性并使用嵌套循环遍历所有项并提取vm属性,然后获取索引处的项并添加到变量中。 Push this value to an array:将此值推送到数组:

var res = [];
jsonData.data[0].vm.forEach((e, i) => {
  let sum = 0;
  jsonData.data.forEach(f => sum += f.vm[i]), res.push(sum)
})

Demo:演示:

 const jsonData={data:[{name:"13_WH1",attributes:{bv:145},vm:[4,8,6,6]},{name:"32_WH2",attributes:{bv:155},vm:[5,7,7,2]}]}; var res = []; jsonData.data[0].vm.forEach((e, i) => {let sum = 0; jsonData.data.forEach(f => sum += f.vm[i]), res.push(sum)}) console.log(res);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM