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
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
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
For example:
var total = fundsBeingSold.sliderValueArr.reduce((a, b) => a + b);
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();
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
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);