-4

I have an object called fundsBeingSold. This object contains an Array[] of numbers named sliderValueArr.

If this array has three values..

0: 59
1: 10
2: 12

how do I set a variable to be the sum of these values?

Thanks

3

4 Answers 4

0
var fundsBeingSold = {
    sliderValueArr: [59, 10, 12]
};

var sum = fundsBeingSold.sliderValueArr.reduce(function(a, b) {
    return a + b;
});

console.log(sum) // will print the sum 81
Sign up to request clarification or add additional context in comments.

Comments

0

For example:

var total = fundsBeingSold.sliderValueArr.reduce((a, b) => a + b);

Comments

-1

Use reduce:

var sum = fundsBeingSold.sliderValueArr.reduce(function(a,b){return a+b;},0);

You could also use JQuery for that:

$.each(fundsBeingSold.sliderValueArr,function(){sum+=parseFloat(this) || 0;});

If you want, you could also add a prototype to do it faster, like so:

Array.prototype.sum = function() {
  return this.reduce(function(a,b){return a+b;});
}

And you would use it like this: var mySum = fundsBeingSold.sliderValueArr.sum();

Comments

-1

you can do :

var fundsBeingSold = {
    sliderValueArr: [59, 30, 42]
};

var s = sum();

function sum() {
  s = 0;
  var i;
  for (i = 0; i < fundsBeingSold.sliderValueArr.length ; i++) {
    s += fundsBeingSold.sliderValueArr[i];
  }
  s;
  return s;
}

console.log(s);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.