猿问

在多个子数组中使用脚本减少函数

我试图计算值计数,如果通用=== 在多个子数组下为真,但我没有成功如何使用java脚本减少函数来获得总计4


总和应为 4,因为只有 4 个对象具有共同点 === 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); 


喵喔喔
浏览 127回答 3
3回答

慕容708150

您将嵌套数组作为对象的值,您需要两个内部循环来获取所需的求和属性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

有只小跳蛙

另一种方法是使用以下方法拼合数组,然后应用:concatreduceconst 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}`);

隔江千里

这是另一种方式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);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答