DEV Community

Cover image for Summing properties from a list of objects in JS
Alisson Zampietro
Alisson Zampietro

Posted on

3 3

Summing properties from a list of objects in JS

Let's assume that we have an array of objects called products with the following structure:

let products = [
  {
     "name": "Item 1",
     "price": 20,
     "vat": 4
  },
  {
     "name": "Item 2",
     "price": 40,
     "vat": 10
  }
]
Enter fullscreen mode Exit fullscreen mode

So, if we want to sum all numbers (price+vat) let's make the following steps:

1-We call the map() function to generate an array with the numeric values that we want to sum:

products.map(
  product => ([product.vat, product.price])
)
// result: [[20, 4], [40, 10]]
Enter fullscreen mode Exit fullscreen mode

2-We flatten the list with the method flat():

.flat()
// result: [20, 4, 40, 10]
Enter fullscreen mode Exit fullscreen mode

3-We sum all values with the reduce() method:

.reduce((a, b) => a + b)
// result: 74
Enter fullscreen mode Exit fullscreen mode

In the end we get this code:

let total = products.map(product =>([product.vat,product.price])).flat().reduce((a, b) => a + b)
Enter fullscreen mode Exit fullscreen mode

Thank you!

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay