0

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");
Community
  • 1
  • 1
Sylar
  • 11,422
  • 25
  • 93
  • 166

4 Answers4

4

Define a generic sum function, which is as trivial as

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

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((x, y) => x + y);
  
let totalAmount = sum(array.map(x => Number(x.amount)));
  
console.log(totalAmount.toFixed(2))
  
  
georg
  • 211,518
  • 52
  • 313
  • 390
2

Please try:

Array.prototype.sum = function (prop) {
    var total = 0
    for ( var i = 0, _len = this.length; i < _len; i++ ) {
        total += parseFloat(this[i][prop]) // Surely this will work :)
    }
    return total
};
Parminder Singh
  • 351
  • 1
  • 10
0

const array = [
 {quantity: 1, amount: "24.99"},
 {quantity: 5, amount: "4.99"}
]
  
Array.prototype.sum = function(key) {
  return this.reduce(function(total, item) {
    return total + parseFloat(item[key]);
  }, 0);
}

// weird javascript math ...
console.log(array.sum("amount"));

// workaround
console.log(array.sum("amount").toFixed(2));

This work fine ;)

Steeve Pitis
  • 4,283
  • 1
  • 21
  • 24
0

I usually use the reduce() method for situations like these. Here is a little demo: http://codepen.io/PiotrBerebecki/pen/zKEQgL

let array = [
 {quantity: 1, amount: "24.99"},
 {quantity: 5, amount: "4.99"}
]

function sumProperty(arr, type) {
  return arr.reduce((total, obj) => {
    if (typeof obj[type] === 'string') {
      return total + Number(obj[type]);
    }
    return total + obj[type];
  }, 0);
}

let totalAmount = ( sumProperty(array, 'amount') ).toFixed(2); 
console.log(  totalAmount  ); // 29.98

let totalQuantity = sumProperty(array, 'quantity'); 
console.log(  totalQuantity  ); // 6
Piotr Berebecki
  • 7,428
  • 4
  • 33
  • 42