简体   繁体   中英

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. Some of these datasets can get to be 100s of records, so being fast is important.

# 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.

 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. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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