0

I'm prompting the user to enter how many numbers they would like to store in an array. Then I prompt user to enter each individual number and push this into an array, I can display the numbers correctly but now what I'm trying to do is add up all the values. I've searched through the site and there's several solutions but still having problems making my example work. This is the code I have so far.

function howManyValues(userValues) { 
    for(var i=0;i<userValues;i++) {
        myArray=[];
        myArray.push(prompt("Enter value postion"+i));
        
        document.write("These are the values you have entered: "+myArray+"<br>");
    }
} 

var userValues=prompt("How many values do you want to work with: ");
howManyValues(userValues);
fubar
  • 16,918
  • 4
  • 37
  • 43
Daniel R
  • 15
  • 5
  • As I understood, if someone for example entred 2 values to be added to the array, then he enters 2, then 3, then you would calculate the sum if his input and show it, for example 5 in my exame ? Am I right ? – ThS Aug 28 '18 at 22:19
  • Your interpretation of what I was trying to accomplish is correct. – Daniel R Sep 01 '18 at 17:41

7 Answers7

2

Lets start with the mistake in your existing code.

You are re-initialising myArray inside your for loop. This will reset myArray to an empty array on each iteration of the loop. You need to move this variable outside of your loop.

Next, you are using a for loop to prompt the user to enter however many numbers they specify. That's great. It would be more user friendly if the number prompt started at 1, rather than 0.

And finally on to your question. How to sum the values. You're already looping through and capturing the user values as they're entered. The simple solution would be to sum the values as they're entered.

Notice that the captured value is being cast to a Number before summing. This is because prompt will return the value as a String, not a Number.

function howManyValues(count) {
    var values = [];
    var sum = 0;

    for (var i = 1; i <= count; i++) {
        var value = prompt('Enter value ' + i);
        
        values.push(value);
        sum += Number(value);

        document.write('These are the values you have entered: ' + values.join(', ') + '<br>');
    }

    document.write('The values entered have a sum value of: ' + sum + '<br>');
}


var count = prompt('How many values do you want to work with?');
howManyValues(count);
fubar
  • 16,918
  • 4
  • 37
  • 43
  • Thanks for the explanation on the problem I was creating by re initializing myArray by including this in the for loop. I had forgotten that using prompt returns the value as a string, it seemed cleaner using the approach that @Sam Littlefair used by using the following: myArray.push(parseInt(prompt. I was able to follow your solution and found it to wor. I do have a question regarding values.join(', ') wouldn't this be the same as writing values in the document.write line? Tried both ways and got the same results. – Daniel R Aug 29 '18 at 03:13
  • @DanielR, concatenating the array into a string will invoke the `toString()` method on the array. This will separate the values with a comma, but no space. Using `join(', ')` just looked a little neater in the output to me. – fubar Aug 29 '18 at 04:49
  • Taking your advised in making the initial message more user friendly if the number prompt started at 1, rather than 0. I initialized var i =1 and to display the individual values for the array used document.write(userArray[i-1]+"
    ");
    – Daniel R Sep 01 '18 at 17:32
0

You can either use a forloop, or reduce for that.

reduce:

myArray.reduce((prev, curr) => prev += curr, 0) // returns 15

for-loop:

let result = 0
for (let i = 0; i < myArray.length; i++) {
   result += myArray[i]
}

// result is 15

edit: @fubar's solution suits your code perfectly.

0

You might be interested in array.reduce, which is perfect for transforming an array into a single value, such as a sum. Notice I've transformed input strings into numbers and restructured your code to separate concerns. Error handling is left as an exercise.

const sum = a => a.reduce((a, e) => a + e, 0);

const collectInput = count =>
  [...Array(count)].map(() => prompt("Enter a value:"));

const count = +prompt("How many values do you want to work with: ");
const total = sum(collectInput(count).map(Number));
alert("total is: " + total);
ggorlen
  • 44,755
  • 7
  • 76
  • 106
0

You are declaring myArray as an empty array at each loop, that needs to be moved outside.

Then to add up, you can use reduce:

myArray.reduce((a, b) => a + b, 0)

So your code should be something like:

function howManyValues(userValues) { 
    myArray=[];
    for(var i=0;i<userValues;i++) {
        myArray.push(parseInt(prompt("Enter value postion"+i)));
        document.write("These are the values you have entered: " + myArray[i] + "<br>");
    }
    document.write("The total of the values you have entered: " + myArray.reduce((a, b) => a + b, 0) + "<br>");
} 

var userValues=prompt("How many values do you want to work with: ");
howManyValues(userValues);
Sam
  • 608
  • 4
  • 11
  • 1
    This line myArray.push(parseInt(prompt.. is definitely useful and will be making note of this. Seems very clean and avoids extra steps converting the value entered in prompt to a number. I will have to practice more using myArray.reduce((a, b) => a + b, 0) to sum up results. – Daniel R Aug 29 '18 at 03:20
0

Arrays Objects allow Discord to store keyed collections of values. That’s fine.

But quite often we find Adobe Reader that we need an ordered collection, where we have a 1st, a 2nd, a 3rd element and so on. For example, we need that to store a list of something: users, goods, HTML elements etc.

It is not convenient to use an object here,iTunes because it provides no methods to manage the order of elements. We can’t insert a new property “between” the existing ones. Objects are just not meant for such use.

There exists a special data structure named Array, to store ordered collections.

jackmo120
  • 1
  • 1
0
<script>
    function howManyValues(userValues) {
        let myArray = [];
        let sum = 0;

        for(let i = 0; i < userValues; i++) {
            let newVal = prompt("Enter value postion " + i);
            myArray.push(newVal);
            sum += parseInt(newVal);
        }
        document.write("The values you entered are " + myArray.join(', ') + " and their sum is " + sum + "<br>");
    }

    let userValues=prompt("How many values do you want to work with: ");
    howManyValues(userValues);
</script>
Chukwuemeka Inya
  • 2,575
  • 1
  • 17
  • 23
0

This was my final answer on this.

function getUserInput(numbers){
userArray=[];
for(var i=1;i<=numbers;i++){
userArray.push(parseInt(prompt("Enter the No. "+i+" value: ")));
document.write(userArray[i-1]+"<br>");
}

document.write("The total for this array is: 
"+userArray.reduce((a,b)=>a+b,0));
}

var numbers=prompt("How many numbers do you want to enter: "); 
getUserInput(numbers);
Daniel R
  • 15
  • 5