javascript
Array reducce
sum an array of objects
//Reference -> https://sebhastian.com/javascript-sum-array-objects/
//Sometimes, you need to count the sum of property in an array of objects.
//For example, you may find an array of items, and you want to sum the total quantity a person must pay for the items
let cart = [
{
name: "JavaScript book",
price: 4,
},
{
name: "UGG Women's Hazel Ankle Boot",
price: 79,
},
{
name: "OXO Good Grips 11-Inch Balloon Whisk",
price: 9,
},
];
// totalPrice is 92
let totalPrice = cart.reduce(function (accumulator, item) {
return accumulator + item.price;
}, 0);
//Perform multiple operations before returning the data
let cart = [
{
name: "JavaScript book",
quantity: 3,
price: 4,
},
{
name: "UGG Women's Hazel Ankle Boot",
quantity: 2,
price: 79,
},
{
name: "OXO Good Grips 11-Inch Balloon Whisk",
quantity: 5,
price: 9,
},
];
// totalPrice is 215
let totalPrice = cart.reduce(function (accumulator, item) {
return accumulator + item.quantity * item.price;
}, 0);
//Filter the array before reduce
let cart = [
{
name: "JavaScript book",
quantity: 3,
price: 4,
},
{
name: "UGG Women's Hazel Ankle Boot",
quantity: 2,
price: 79,
},
{
name: "OXO Good Grips 11-Inch Balloon Whisk",
quantity: 5,
price: 9,
},
];
// totalPrice is 170
let totalPrice = cart
.filter(
(item) =>
item.name === "JavaScript book" ||
item.name === "UGG Women's Hazel Ankle Boot"
)
.reduce((accumulator, item) => {
return accumulator + item.quantity * item.price;
}, 0);
Was this helpful?
Similar Posts
- Sort array using Array.sort() in javascript
- Break an array into fixed length array groups using lodash in Javascript
- Get all values from an array which does not exist in other array Lodash
- Convert a string to array using Array.from() in javascript
- Collect books from array of objects and return collection of books as an array
- Javascript Code for Sorting array and finding Largest No. in Array
- Array.forEach() in javascript