1

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?

Fiddle DEMO

5
  • by required you mean elements that satisfy a condition ? Commented Sep 25, 2018 at 16:38
  • 1
    you need to be more clear, what is required sum? is it the number for elements from the array you want to sum, or soething else. Commented Sep 25, 2018 at 16:39
  • @Vaibhav, thanks, edited. I mean the numer of elements. Commented Sep 25, 2018 at 16:40
  • i finally understood the question, he wants to sum only the first n values of the array, and n = input number. Commented Sep 25, 2018 at 16:40
  • 1
    add first n elements of an array is what you need to search on google. Commented Sep 25, 2018 at 16:45

4 Answers 4

4

There are at least two ways:

  1. 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

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

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

1 Comment

This answer encourages improving fishing skills. Good answer!
1

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/

Comments

1

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/

Comments

1

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.

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.