简体   繁体   中英

Javascript reduce function use in multiple child array

I am trying to count value count if common === true under multiple child array but i am not succeed how to use java script reduce function for get total 4

total sum should be 4 because only 4 object has common === true

const obj = {
  "A": [
    [
      {
        "count": "1.00",
        "common": false
      },{
        "count": "1.00",
        "common": true
      }
    ],
    [
      {
        "count": "1.00",
        "common": false
      },
      {
        "count": "1.00",
        "common": true
      }
    ]
  ],
  "B": [
    [
      {
        "count": "1.00",
        "common": false
      },{
        "count": "1.00",
        "common": true
      }
    ],
    [
      {
        "count": "1.00",
        "common": false
      },
      {
        "count": "1.00",
        "common": true
      }
    ]
  ]
};

let total = Object.values(obj).reduce((acc, value) => acc + value.reduce((a,b) => a+b.reduce((c,d) => c + (d.common) ? parseInt(d.count) : 0,0),0), 0); 

Here is another way

 const obj = { "A": [ [ { "count": "1.00", "common": false },{ "count": "1.00", "common": true } ], [ { "count": "1.00", "common": false }, { "count": "1.00", "common": true } ] ], "B": [ [ { "count": "1.00", "common": false },{ "count": "1.00", "common": true } ], [ { "count": "1.00", "common": false }, { "count": "1.00", "common": true } ] ] }; let total = 0; Object.values(obj).forEach(c => c.forEach(arr => total += arr.filter(o => o.common).length)); console.log("Total: " + total);

You have nested arrays as values of the object, you need two inner loops to get the wanted properties for summing

 const obj = { A: [[{ count: "1.00", common: false }, { count: "1.00", common: true }], [{ count: "1.00", common: false }, { count: "1.00", common: true }]], B: [[{ count: "1.00", common: false }, { count: "1.00", common: true }], [{ count: "1.00", common: false }, { count: "1.00", common: true }]] }, total = Object.values(obj).reduce((r, outer) => { outer.forEach(inner => inner.forEach(({ common, count }) => r += common? +count: 0) ); return r; }, 0); console.log(total); // 4

Another way would to flatten the array using concat and then apply reduce :

 const obj = { "A": [ [{"count": "1.00", "common": false}, {"count": "1.00", "common": true}], [{"count": "1.00", "common": false}, {"count": "1.00", "common": true}] ], "B": [ [{"count": "1.00", "common": false}, {"count": "1.00", "common": true}], [{"count": "1.00", "common": false}, {"count": "1.00", "common": true}] ] }; const sum = [].concat(...([].concat(...Object.values(obj)))).reduce(( acc, cur ) => acc + (cur.common? +cur.count: 0), 0) console.log(`Total count = ${sum}`);

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