yoora
yoora

Reputation: 65

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.

Upvotes: 1

Views: 172

Answers (3)

Maheer Ali
Maheer Ali

Reputation: 36564

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));

Upvotes: 1

deepak_pal
deepak_pal

Reputation: 159

let res = 0;
arr.forEach((data1,index,arr)=>{
    data1.forEach(({qunt})=>{
        res+=qunt
    })
})
console.log(res)

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44087

Just use map and reduce:

const quantities = arrayOfArraysOfObjects.map(a => a.reduce((acc, { quantity }) => acc + +quantity, 0));

Upvotes: 1

Related Questions