Skip to content Skip to sidebar Skip to footer

Add Sums Of Array. Display One Output

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

Solution 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 0console.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);

Solution 2:

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.

Solution 3:

var arr = [];                               // define our arrayfor (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 resultvar 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 caseconsole.log(a + "A"); //used for debug
    }

Post a Comment for "Add Sums Of Array. Display One Output"