EN
JavaScript - sum property values in array of objects
0
points
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