const refunds = [ { request_amount_to_refund: "3000", entity_id: "1850231228424", is_zni: false }, { request_amount_to_refund: "2000", entity_id: "1850231228422", is_zni: false }, { request_amount_to_refund: "1000", entity_id: "1850231228422", is_zni: true }, { request_amount_to_refund: "500", entity_id: "1850231228422", is_zni: true } ] const refundsFormatted = Object.values(refunds.reduce((acc, curr) => { const valueId = `${curr.entity_id}-${curr.is_zni}` // Does value already exist ? const existingValue = acc[valueId] // Values to add const existingRequestAmount = parseInt(existingValue?.request_amount_to_refund ?? 0) const newRequestAmount = parseInt(curr?.request_amount_to_refund ?? 0) const quantity = existingValue?.quantity ? existingValue?.quantity + 1 : 1 const newValue = { ...curr, request_amount_to_refund: existingRequestAmount + newRequestAmount, quantity: quantity } return ({ ...acc, [valueId]: newValue, }) }, {})) console.log(refundsFormatted) /** Output expected [ { request_amount_to_refund: "3000", entity_id: "1850231228424", is_zni: false, quantity: 1 }, { request_amount_to_refund: "2000", entity_id: "1850231228422", is_zni: false, quantity: 1 }, { request_amount_to_refund: "1500", entity_id: "1850231228422", is_zni: true, quantity: 2 } ] */
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter