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);
-
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– ThS2018年08月28日 22:19:01 +00:00Commented Aug 28, 2018 at 22:19
-
Your interpretation of what I was trying to accomplish is correct.Daniel R– Daniel R2018年09月01日 17:41:12 +00:00Commented Sep 1, 2018 at 17:41
7 Answers 7
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);
3 Comments
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.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);
1 Comment
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.
Comments
<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>
Comments
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.
Comments
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);
Comments
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);