I need to sum some object values in an array. Some can be int
while others can be string
ie:
JavaScript:
let array = [
{quantity: 1, amount: "24.99"}
{quantity: 5, amount: "4.99"},
]
Digging around Stack Overflow I have found this method (Im using React):
Array.prototype.sum = function (prop) {
var total = 0
for ( var i = 0, _len = this.length; i < _len; i++ ) {
total += this[i][prop]
}
return total
};
let totalQuantity = array.sum("quantity");
console.log(totalQuantity);
While that works great, I need to do the same for the string amount
. Since I need to convert amount
into float, the above will not work. React complains about Component's children should not be mutated.
Not being JS ninja, I thought this would do some magic:
Array.prototype.sum = function (prop) {
var newProp = parseFloat(prop);
var total = 0
for ( var i = 0, _len = this.length; i < _len; i++ ) {
total += this[i][newProp] // Surely this is wrong :(
}
return total
};
Any clean way to achieve this?
I need this:
let totalAmount = array.sum("amount");