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

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Good catch. I was wondering if there's another way instead of using Array.prototype
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
};

2 Comments

Ahhhhhhh! Thanks for that. It's good to have another eye to look at things.
@Sylar take a look to the array.reduce version ;)
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 ;)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.