Reputation: 1325
I need to Sum all elements of array, up to the selected value of input (first four elements in this example):
HTML:
<input id="VAL" value="4" />
<button onclick="SUM()">BUTTON</button>
SUM: <span id="bubu"></span>
JS:
var numbers = [1, 2, 3, 4, 5];
function getSum(x,y) {return x+y;}
function SUM() {
document.getElementById("bubu").innerHTML = numbers.reduce(getSum);
}
Now the sum of all elements work correctly. But how can I add a loop, to get only required sum?
Upvotes: 1
Views: 167
Reputation: 5250
Using a for loop
, it's pretty simple.
var numbers = [1, 2, 3, 4, 5];
let upTo = 4;
var res = 0;
for(let i = 0; i<upTo; i++){
res += numbers[i];
}
console.log(res)
Using reduce()
var numbers = [1, 2, 3, 4, 5];
let upTo = 4;
var res = numbers.reduce((a,e,i)=>(i<upTo)?a+e:a+0)
console.log(res)
Example: https://jsfiddle.net/fsbhoe45/
Upvotes: 1
Reputation: 2236
You could also do this using reduce
alone if you supplied a limit
to handler that indicates the index up to which you need the sum for. For e.g. if you need sum up to 4 elements then limit is 3.
function onClickHandler(limit) {
return numbers.reduce(function (acc, val, index) {
return index < limit ? acc : acc + val
}, 0)
}
Hope this helps.
Upvotes: 1
Reputation: 521
Use the reduce index parameter: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
var numbers = [1, 2, 3, 4, 5];
window.SUM = function() {
var numberOfElements = document.getElementById("VAL").value;
document.getElementById("bubu").innerHTML = numbers.reduce(function(x, y, i){
if(i <= numberOfElements-1) {
return x+y;
} else {
return x;
}
});
}
https://jsfiddle.net/k9vrLsnm/3/
Upvotes: 1
Reputation: 1074048
There are at least two ways:
filter
slice
first, removing the values you don't want to sum up (edited because of the OP's comment "I mean the numer of elements"), or
In your reduce
callback, don't add y
if it's not one of the values you want to include (by checking the index you receive as the third argument to the callback)
Upvotes: 4