1

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.

3 Answers 3

1

Just use map and reduce:

const quantities = arrayOfArraysOfObjects.map(a => a.reduce((acc, { quantity }) => acc + +quantity, 0));
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.