-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

David Gourde
  • 3,709
  • 2
  • 31
  • 65
Mike
  • 2,391
  • 6
  • 33
  • 72

5 Answers5

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
Timur Ridjanovic
  • 1,002
  • 1
  • 12
  • 18
0

For example:

var total = fundsBeingSold.sliderValueArr.reduce((a, b) => a + b);
rsp
  • 107,747
  • 29
  • 201
  • 177
-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();

David Gourde
  • 3,709
  • 2
  • 31
  • 65
-1

you can do that operation using jQuery.map such as:

let arr = [ 59, 10, 12];
let result = 0;
jQuery.map(arr, function(str, i){
  return result += str
})

But you don't necessarily need jQuery you can do that with vanilla javascript using map as well, such as:

let arr = [ 59, 10, 12];
let result = 0;
arr.map(function(str) {
   result += str;
}

I hope that helps,

Bruno

Bruno Barbosa
  • 94
  • 1
  • 7
-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);