0

Update: The answer to this question is bellow. Thanks to dougtesting on a different thread. add array together, display sum

function hello() {
    var arr = [];

    for (var i = 0; i < 10; i++) {
        arr.push(prompt('Enter number' + (i+1)));
    }

    var total = 0;

    for(i=0; i<arr.length; i++) {
        var number = parseInt(arr[i], 10);
        total += number;
    }

    console.log(total);
}

//End of answer.

I am trying to have a user input 10 numbers. Then add those numbers together and display the output to the user. I was able to get the amount of inputs (10) into a array but I can't get arrays contents. I feel like I'm missing something simple. Would you mind taking a look?

// https://stackoverflow.com/questions/28252888/javascript-how-to-save-prompt-input-into-array
var arr = [];                               // define our array

for (var i = 0; i < 10; i++) {              // loop 10 times
  arr.push(prompt('Enter number' + (i+1))); // push the value into the array
}

alert('Full array: ' + arr.join(', '));    // alert the result

var arrEquals = []; //Empty Arr
 arrEquals = arr.push(); //turn string into var

alert (arrEquals);//show string to admin for debug

//(for loop) console out # of  array elements. does not output what is in array
//this is half the battle  
    for (var a = 0; a < arrEquals; a++){
         var a = Number(a); //ensure input is Number()
           console.log(a + "A"); //used for debug
    }


//taks sums in array and adds them together
//this is the other half of the problem
// https://www.w3schools.com/jsref/jsref_forEach.asp   
// var sum = 0;
// var numbers = [65, 44, 12, 4];

// function myFunction(item) {
//     sum += item;
//     demo.innerHTML = sum;
// }
2
  • arrEquals = arr.push(); //turn string into var - That comment is wrong about what that line does. That line is throwing away the array that you created on the previous line with arrEquals = [] and replacing it with the value returned by .push() (which isn't an array). You don't need this second array at all if you just want the total of the numbers, you can loop over the arr array directly. Commented Aug 16, 2017 at 3:55
  • Did you debug your code? Commented Aug 16, 2017 at 4:02

3 Answers 3

1

This is probably one of the simplest examples of something that Javascript's built in array .reduce() function would be used for. Effectively, you're "reducing an array to a single value".

A reduce works by taking an array and running a function on each item. This "callback" function receives the value that the previous function returns, processes it in some way, then returns a new value. Worth noting, the reduce function also takes a 2nd argument that acts as the initial value that will be passed to the callback function the first time.

array.reduce(callbackFunction, initialValue);

Here's an example of reduce being used to sum an array.

var result = [1,2,3,4,5,6,7,8,9,10].reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
}, 0); // start with an initial value of 0
console.log(result);

Using ES6 syntax, this can be further simplified to a one-liner

var result = [1,2,3,4,5,6,7,8,9,10].reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(result);

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

2 Comments

.reduce() is the "best" solution, but the answer would be better if it related more directly back to the OP's code given that they're starting with an array of strings. (Also, note that for just adding a list of numbers you don't need to pass the initial 0 in the second argument.)
@nnnnnn yeah, I was mainly trying to round out the answers. I also included the initial value for completeness since it's needed in most reduce operations (it also helps to avoid any weirdness, with the accumulator being populated by undefined or null values).
0

In your loop you're referencing arrEquals like for (var a = 0; a < arrEquals; a++){. you need to reference it like for (var a = 0; a < arrEquals.length; a++){ because just referencing the array doesn't tell javascript how long it is, or what number to count to. the .length returns a number, that number is how many items are in the array.

Comments

0
var arr = [];                               // define our array

for (var i = 0; i < 10; i++) {              // loop 10 times
  arr.push(prompt('Enter number' + (i+1))); // push the value into the array
}

arr = arr.join(', ');
alert('Full array: ' + arr);    // alert the result

var arrEquals = []; //Empty array
 arrEquals.push(arr); //assign arr string to an empty array

alert (arrEquals[0]); //show array[0] string to admin for debug

Is this what you are looking for? You need to put the arr.join() result to a variable, like itself.

You shouldnt be using arr.push() at all if you're not pushing new array items on it

//(for loop) console out # of  array elements. does not output what is in array
//this is half the battle  
    for (var a = 0; a < arrEquals.length; a++){
          //a is always a int in this case
           console.log(a + "A"); //used for debug
    }

3 Comments

As to the use of the first text box area, this was someone else's work that i was using to see that i could access items in a array then output those items to the user. The var arrEquals is my attempt to access the array. my logic is to have user enter numbers into array. Loop through each number. Add each number together in array. Display output to user.
Now for the for loop, inside should i then have a be pushed into a empty array to store those new values?
@WalterPurvis yes you're going to have to use array.push() method to dynamically add new values into an array without affecting the already existing values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.