javascript 对对象数组中字段值求和

shyt4zoc  于 2023-02-15  发布在  Java
关注(0)|答案(2)|浏览(209)

从csv文件中获取数据,然后分配给对象数组SmartPostShipments []。使用.length属性输出数组中元素的“总数”非常简单。但我还需要得到名为['Net Charge Amount']的对象数组中每个字段值的sum。完成此操作的最佳方法是什么?对于这个示例,我可以使用console.log()

const { parse } = require('csv-parse')
const fs = require('fs')
const SmartPostShipments = []

function isSmartpost(shipment) {
    return shipment['Service Type'] === 'SmartPost'
}

fs.createReadStream('test.csv')
    .pipe(parse({
        columns: true
    }))
    
    .on('data', (data) => {
        if (isSmartpost(data)) {
            SmartPostShipments.push(data)
        }

 })
    .on('error', (err) => {
        console.log(err)
    })

 .on ('end', () => {
        
    // This outputs each individual 'net charge amount', but how do I just display the sum 
    // total?
    
    console.log(SmartPostShipments.map((shipment)=> {
            return shipment['Net Charge Amount']
        }))
        
       console.log(`${SmartPostShipments.length} Smartpost shipments.`)
     
    })

一些代码建议看起来不错,但是数据是附加的而不是求和的。下面是输出的图片:

console.log(SmartPostShipments.map((shipment)=> {
        return shipment['Net Charge Amount']
    }))
            
    const sum = SmartPostShipments.reduce((partialSum, shipment) => partialSum + shipment['Net Charge Amount'], 0)
    console.log(sum)

    const sumSP = SmartPostShipments.reduce((cur, pre)=> {
        return cur+=pre['Net Charge Amount'];
      },0)
      console.log(sumSP)

lxkprmvk

lxkprmvk1#

const sum = SmartPostShipments.reduce((cur, pre)=> {
  return cur+=pre['Net Charge Amount'];
},0)
console.log(sum)

请尝试以上方法。希望有效。

ru9i0ody

ru9i0ody2#

这是this question的一个变体。根据您的情况,代码将是:

const sum = SmartPostShipments.reduce((partialSum, shipment) => partialSum + shipment['Net Charge Amount'], 0)

相关问题