Calculate the total sum of an array and show only one result

Update: The solution to this query is provided below, courtesy of dougtesting from a different discussion. 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 response.

I am attempting to allow a user to input 10 numbers, then add those numbers together and show the result to the user. I managed to store the number of inputs (10) in an array, but I am unable to access the contents of the arrays. It seems like I might be overlooking something simple. Would you kindly review and assist me with this issue?

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

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

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

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

alert (arrEquals);//displaying string for debugging

//(for loop) printing out # of elements in the array. unfortunately does not output the array content
//this is only half of the solution  
    for (var a = 0; a < arrEquals; a++){
         var a = Number(a); //ensuring input as Number()
           console.log(a + "A"); //used for troubleshooting
    }


//computing sums in array and adding them together
//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;
// }

Answer №1

This is a straightforward example showcasing the usage of JavaScript's built-in array .reduce() function. Essentially, it involves reducing an array to a single value.

The reduce method operates by applying a function to each element in the array. This "callback" function receives the return value from the previous computation, processes it accordingly, and then returns a new value. It's important to mention that the reduce function can also accept a second argument serving as the initial value passed to the callback function on the first iteration.

array.reduce(callbackFunction, initialValue);

Below is an illustration of using reduce to calculate the sum of an array:

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

With ES6 syntax, this process can be further condensed into a one-liner:

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

Answer №2

When writing your loop, make sure to properly reference arrEquals. Instead of using

for (var a = 0; a < arrEquals; a++){
, you should use
for (var a = 0; a < arrEquals.length; a++){
. By including .length after arrEquals, JavaScript will know how many items are in the array and what number to count to.

Answer №3

let numbersArray = [];                               // initializing an empty array

for (let counter = 0; counter < 10; counter++) {              // looping 10 times
  numbersArray.push(prompt('Enter number' + (counter + 1))); // adding input value to the array
}

numbersArray = numbersArray.join(', '); // converting array to string with commas
alert('Full array: ' + numbersArray);    // displaying the result

let newArray = []; // Initializing a new empty array
newArray.push(numbersArray); // Assigning the original array string to the new array

alert(newArray[0]); // Displaying the first element of the new array for debugging

Is this the solution you were seeking? Remember to assign the result of arr.join() to a variable.

Avoid using arr.push() if not adding new elements to the array.

// Loop through and console log the number of array elements, does not output array contents
// This is a step towards solving the issue  
for (let index = 0; index < newArray.length; index++){
      console.log(index + " - Index"); // Used for troubleshooting
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Browsersync functionality in Docker

My Node.js app is facing an issue with Gulp, Browsersync, and Docker. When I run gulp watch locally, everything functions correctly. However, when I utilize docker-compose up, I encounter an error Cannot GET / The Browsersync UI on port 3001 is operat ...

What is the method for triggering the output of a function's value with specified parameters by clicking in an HTML

I am struggling to display a random number output below a button when it is clicked using a function. <!DOCTYPE html> <html> <body> <form> <input type="button" value="Click me" onclick="genRand()"> </form> <scri ...

Transform the distinct outcome of a connection in Laravel into an object rather than a member of an array

My request for related user data returns an object within an array $members = CalendarMembers::with("user") ->where('calendar_id', $calendar[0]->calendar_id) ->get(); This is the relationship defined in the code: public functi ...

The process of sorting an array based on another array that has multiple elements

Currently dealing with two arrays: array1 containing elements [1, 2, 3, 4, 5] and array2 containing elements [3, 4]. My goal is to filter out elements in array1 that are also found in array2. The code I have written seems to work fine when array2 has only ...

Using JSON to pass a dynamic array to Morris Chart

My task involves creating a graph using Morris Charts with a dynamic rectangular array. The array consists of a variable number of columns and looks like this: https://i.sstatic.net/89stw.png To achieve this, I attempted to pass the data to Morris Charts ...

Expanding file input fields in Javascript

I am facing an issue with my form and file input. I need to select images from a different folder. echo '<pre>'; var_dump($_FILES); echo '</pre>'; Upon submitting the form, only the last selected image is displayed, but I ...

Utilizing media queries to tailor the pre-designed website and ensure adaptability

I find myself in a situation where I need to make adjustments to my current website to ensure it fits properly on smaller desktop screens. While the site is viewable on all screen sizes, issues arise with screens as small as 14 inches, resulting in an unwa ...

Generate 3D text with Three.js that remains stable even when zooming or panning

Current Three.js version: r79 I am looking to achieve the effect of having a 3D object (specifically a mesh created with THREE.TextGeometry) appear as if it is in a 2D space while always remaining fixed in the same position on the screen, regardless of an ...

Express.js is encountering an issue where the req.body is returning as undefined when using routes imported from another file

As a newcomer to the world of Node.js Express framework, I have been diligently following tutorials and familiarizing myself with the various routes within the Express framework. In order to prepare for API calls and streamline my route organization, I hav ...

If the $_POST['data'] parameter is not defined, it could mean that the data being passed is too large

I am encountering an issue where I need to send a approximately 10MB json data within a textarea named "data". Strangely, when the data size is between 1-2KB, it works perfectly fine. However, with larger json files, the $_POST['data'] appears to ...

Error message "Unable to load / invalid sound with zero-length duration reported on Chrome and Firefox."

Encountered an issue where / invalid sound zero-length duration was reported in Chrome and Firefox. However, the error only appeared in IE10. Here is the code snippet: foo = soundManager.createSound({ id: 'bar', url: '../music/ ...

The TypeScript error message reads: "You cannot assign type 'undefined' to type 'ReactElement'."

I'm encountering an error in my react project TypeScript error Argument of type 'ReactNode' is not compatible with parameter of type 'ReactElement<any, string | JSXElementConstructor<any>> | ReactElement<any, string | JSX ...

Create exclusive combinations by utilizing various arrays or vectors

I have a large number of text files, each containing lines of integer values: 17,1,2,3,4,5,6,7,10,11,12,13,15,16,20,22,24,26,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, 16,1,2,3,4,5,6,7,8,9,10,11,12,16,17,21,26,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, 23,4,5,6,7,8,9,10,12,13 ...

Smoothly scroll through parallax backgrounds

I've implemented a feature where an element moves in relation to scrolling using jQuery: $('#object').css('transform','translateY('+($(window).scrollTop()*.4)+'px)'); Here's the CSS: #object { width: ...

Ways to implement two functions within a single onclick event

Is it possible to call two functions with onclick event? <input id = "test" onclick="func1()"> Can I add another function as well? How would I go about doing that? ...

Open a new lead form in Crm 2013 by clicking a button and automatically passing the details of the

I have integrated an Add New Lead button into the main form on the Homepage for contacts. Clicking this button triggers a script that opens a new form and passes "Crm Parameter FirstSelectedItemId" as a parameter. By selecting a contact and clicking crea ...

unable to implement $http method in angular.js

I am attempting to retrieve data from a web API. When running on a single HTML page, I receive the response with the data successfully. However, if this script is written separately (outside the HTML page), I am unable to fetch the data. This is the first ...

What is the process to insert a record into a table by triggering an AJAX call upon clicking "save

I'm looking to dynamically update a table with data from a database using AJAX. Specifically, I want the table to reflect any new records added by the user without having to refresh the entire page. Below is my JavaScript code snippet for handling thi ...

Is there a way for redux-saga to pause until both actions occur at least once, regardless of the order in which they happen?

Just diving into Redux saga. I'm working on creating a saga that will fetch the initial state for the redux store from our API server. This task involves utilizing two asynchronous sagas: getCurrentUser and getGroups. The goal is to send these ajax ...

Update background to full screen and include text when hovering over DIV

Currently, I am utilizing Bootstrap and have a layout with 6 columns containing icons/text within. I desire to implement a hover effect where each column triggers a background change in transition for the entire section. In addition, text and button elemen ...