简体   繁体   中英

Sum values of objects in arrays of array

I'm trying to sum values from objects. I have array of arrays of objects.

(7) [Array(5), Array(29), Array(32), Array(20), Array(10), Array(1), Array(1)]

need to sum "quantity" value from each array's object separately, eg.:

1: Array(29)
  0:
    id: "PXvWizOLCPbHCUzHxUoK"
    productName: "someProduct"
    productPrice: "146"
    quantity: 3
  1:
    id: "PXvWizOLCPbHCUzHxUoK"
    productName: "someProduct"
    productPrice: "156"
    quantity: 7 
   etc...

in other words, need to get total sum of "quantity" for all objects in array[1], array[2]...

Some attempts:

1)

 let quantityOfProduct = arrayOfArraysOfObjects[0].reduce((acc, current) => { return{ quantity: acc.quantity + current.quantity } }) 

2)

 let result:any = [] arrayOfArraysOfObjects[0].reduce((acc, current) => { result.push({[current.id]: acc.quantity +current.quantity}) }) 

with above attempts get error "reduce is not define", also I'm using Typescript.

Any suggestion or idea?

Thank You in advance.

Consider arrayOfArraysOfObjects is the name of the variable. You need to use map() on main array and get sum of each array using reduce()

let res = arrayOfArraysOfObjects.map(x => x.reduce((ac,a) => ac + a.quantity,0));

只需使用mapreduce

const quantities = arrayOfArraysOfObjects.map(a => a.reduce((acc, { quantity }) => acc + +quantity, 0));
let res = 0;
arr.forEach((data1,index,arr)=>{
    data1.forEach(({qunt})=>{
        res+=qunt
    })
})
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