Languages
[Edit]
EN

JavaScript - sum property values in array of objects

0 points
Created by:
Jun-L
963

In this article, we would like to show you how to sum property values in an array of objects in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const sumProperty = (array, property) => {
    return array.reduce((a, b) => a + (b[property] || 0), 0);
};


// Usage example:

const items = [
    { name: 'item1', quantity: 1 },
    { name: 'item2', quantity: 2 },
    { name: 'item3', quantity: 3 },
];

console.log(sumProperty(items, 'quantity')); // 6

 

Creating class with sum() method

In this example, we create ItemsCollection class with sum() method that sums the quantity of items.

// ONLINE-RUNNER:browser;

class ItemsCollection extends Array {
    sum(property) {
        return this.reduce((a, b) => a + (b[property] || 0), 0);
    }
}
const items = new ItemsCollection(...[
   { name: 'item1', quantity: 1 },
   { name: 'item2', quantity: 2 },
   { name: 'item3', quantity: 3 },
]);

console.log(items.sum('quantity')); // 6

 

References

  1. Array.prototype.reduce() - JavaScript | MDN

Alternative titles

  1. JavaScript - sum property value in array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join