0

What do I have wrong here? Please feel free to critisise and shame my question formatting, I'm trying to learn how best to ask these questions.

E.g.

{sellerID1: 26.52, sellerID1: 12.46, sellerID2: 72.39}

const cartItems = [{
        "oq23jnq89vj3": {
            sellerID: "aj8f9b73h2v37fy",
            productPrice: 3.99
        }
    },
    {
        "p98nq4hn984t": {
            sellerID: "aj8f9b73h2v37fy",
            productPrice: 19.99
        }
    },
    {
        "vzly89nvhj08": {
            sellerID: "zwlvin3u598n84w",
            productPrice: 10.00
        }
    }
]
for (const item in cartItems) {
    const sellerTotals = {}
    const sellerIDs = {}
    const productPrice = {}
    sellerIDs.push[item.sellerID]
    productPrice.push[item.productPrice]
    const sellerTotals = [...SellerIDs, ...productPrice] where SellerIDs "=="
    SellerIDs
}
console.log(sellerTotals)
// Desired return { sellerID1: 23.98, sellerID2: 10.00}
Mars2024
  • 364
  • 3
  • 15
  • 1
    do you have some data and wanted result? – Nina Scholz Dec 01 '21 at 21:25
  • Hi yes my data is the `[sellerID1: 26.52, sellerID1: 12.46 sellerID2: 72.39]` and Im trying to merge the values to the desired return of `{ sellerID1: 38.98, sellerID2: 72.39}` – Mars2024 Dec 01 '21 at 21:31
  • 2
    `[sellerID1: 26.52, sellerID1: 12.46 sellerID2: 72.39]` is not valid. please add valid code to the question (and not in comment section). – Nina Scholz Dec 01 '21 at 21:34
  • 1
    You need to use `reduce` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce – Literphor Dec 01 '21 at 21:38
  • 1
    Use reduce method to get the total price: 'items.reduce((a,b)=>a+b)' , this Will sum all the array values, if your values are object just use a.prop and b.prop instead, sorry for the bad formatting but im on mobile. – Mário Santos Dec 01 '21 at 21:40

1 Answers1

0

Thanks to the Reactiflux discord community, this was the solution to my problem of reducing values.

cartItems.reduce((acc, value) => {
        if(acc[value.productSellerUserID]) {
          acc[value.productSellerUserID] += Number(value.productPrice);
        } else {
          acc[value.productSellerUserID] = Number(value.productPrice);
        }
        return acc;
    }, {}),
)
Mars2024
  • 364
  • 3
  • 15