patternjavascriptMinor
Computing the subtotal of all items on their property criteria: qty * price
Viewed 0 times
subtotalthepricecriteriaallpropertyitemsqtytheircomputing
Problem
I have an array which represent the item purchases of a customer, and computed the items subtotal in this logic:
And yes of course I get the correct result, but is there any efficient way to do this in JavaScript?
function getSubtotal(arr) {
let total = 0.00;
arr.forEach(function(i) {
total += (i.qty * i.price)
});
return total; // 1274.21
}And yes of course I get the correct result, but is there any efficient way to do this in JavaScript?
let data = [
{
name : 'Item 1', qty: 2, price: 15.50 // 31
},
{
name : 'Item 2', qty: 17, price: 25.13 // 427.21
},
{
name : 'Item 3', qty: 102, price: 8.00 // 816
}
];
function getSubtotal(arr) {
let total = 0.00;
arr.forEach(function(i) {
total += (i.qty * i.price)
});
return total; // 1274.21
}
document.write(getSubtotal(data));Solution
You are computing the sum of an array, with a twist. Use
Furthermore, if you are going to use the ECMAScript
Better naming would help. "Get" implies that you are retrieving something that already exists, which is not the case here. Also,
Array.reduce() to compute sums.Furthermore, if you are going to use the ECMAScript
let language feature, you should also use arrow function notation.function subtotal(items) {
return items.reduce(
((total, item) => total + item.qty * item.price),
0.00
);
}Better naming would help. "Get" implies that you are retrieving something that already exists, which is not the case here. Also,
i has a connotation of being an index counter, which makes its use in your forEach() confusing.Code Snippets
function subtotal(items) {
return items.reduce(
((total, item) => total + item.qty * item.price),
0.00
);
}Context
StackExchange Code Review Q#158491, answer score: 5
Revisions (0)
No revisions yet.