1

Grabbing data from a csv file then assigning to an object array, SmartPostShipments []. Outputting the "total" number of elements in the array is pretty straightforward by using the .length property, but I also need to get the sum of each field value in the object array called ['Net Charge Amount']. What is the best way to accomplish this? I am fine with using console.log() for this illustration.

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.`)
     
    })

A couple of the code suggestions look good, but the data is appending instead of summing. Here's a pic of the output:

 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)

enter image description here

Derek
  • 475
  • 1
  • 9
  • 18

2 Answers2

4

This is a variation of this question. Applied to your situation the code would be:

const sum = SmartPostShipments.reduce((partialSum, shipment) => partialSum + shipment['Net Charge Amount'], 0)
Austin
  • 41
  • 3
2
const sum = SmartPostShipments.reduce((cur, pre)=> {
  return cur+=pre['Net Charge Amount'];
},0)
console.log(sum)

Please try the above. Hope it works.

tzztson
  • 328
  • 3
  • 22