Sylar Sylar - 2 months ago 33
React JSX Question

Sum of string values on array object

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");

Answer

You've chosen a poor answer:

  • it modifies a global prototype, which is a bad idea
  • the proposed sum function does two unrelated things (pick a property and sum its values).

A better approach would be to define a generic sum function, which is as trivial as

let sum = a => a.reduce((n, x) => n + x);

and apply it to the list of values picked from the source array:

let array = [
 {quantity: 1, amount: "24.99"},
 {quantity: 5, amount: "4.99"}
];
  
let sum = a => a.reduce((n, x) => n + x);
  
let totalAmount = sum(array.map(x => Number(x.amount)));
  
console.log(totalAmount.toFixed(2))