Trouble with Sum Array Function

I've encountered an issue while trying to calculate the sum of a dynamic array. Instead of adding up the numbers, they are just being displayed next to each other. I attempted to sum 1+2+3+4+5, but the output shows as 012345 instead of 15.

let userInput = -1;
const totalInputs = [];
let sum = 0;
let j = 0;

while(userInput !== 999) {
    userInput = window.prompt("Enter a test score, or 999 to end the program");

    if(userInput <= 100 && userInput >= 0) {
        totalInputs[j] = userInput;
        j++;
    }
}

$("lastScore").value = totalInputs[j-1];

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

$("sumScores").value = sum;

When the prompt appears, I input 1, 2, 3, 4, 5 while pressing enter between each value, followed by 999 to end the prompt. However, the result is 012345 instead of the expected 15. I have tried various solutions but cannot figure out why it behaves this way. The $ function simply returns

window.document.getElementById(theId);

Answer №1

Let's make a simple change in the code below:

for(var i = 0; i < totalInputs.length; i++)
{
    sum += +totalInputs[i]; //this makes sure the string is coerced to a number.
}

In JavaScript, converting a = "1" to a = 1 can be easily done by using the unary plus operator like so: a = +a. This kind of coercion is a unique feature of JavaScript.

The reason you are experiencing this issue is because the user input from the prompt box is always treated as a string.

Answer №2

Initially, the script contains numerous typos which made it challenging to get it to function properly.

Here's the breakdown: when a prompt is used, the browser stores the input as a string. If you try to add the string at index 0 with the string at index 1, you will end up concatenating them instead of adding as numbers. To resolve this issue, you can utilize the parseInt function.

var userInput = -1;
var totalInputs = [];
var sum = 0;
var j = 0;

while(userInput != 999)
{
  userInput = window.prompt("Enter a test score, or 999 to end the program");

  if(userInput <= 100 && userInput >= 0)
  {
    totalInputs[j] = userInput;
    j++;
  }
}

$("lastScore").value = totalInputs[j-1];

for(var i = 0; i < totalInputs.length; i++)
{
  sum += parseInt(totalInputs[i]);
}

$("sumScores").value = sum;

By following these steps, the script should now work correctly. Take note of the ParseInt method within the for loop, converting the string into an Integer for proper addition.

To enhance the code further, consider storing the inputs as Integers initially rather than casting them during summation. Update the prompt section from:

userInput = window.prompt("Enter a test score, or 999 to end the program");

To:

userInput = parseInt(window.prompt("Enter a test score, or 999 to end the program"));

This adjustment allows you to remove the parseInt function from the for loop. Hence, modify the line:

// sum += parseInt(totalInputs[i]);
sum += totalInputs[i];

Answer №3

Although one answer has already been marked as correct, I'd like to offer my own perspective. The answers provided above may work in certain cases, but they are prone to bugs due to the unreliable nature of user input.

@Luis's answer is effective, but have you considered inputting alphanumeric characters like 1bs64s? When parsed, it returns just the number 1. This unexpected behavior could be confusing for users, even though it might be acceptable to you. It's crucial to consider the user's perspective when allowing alphanumeric inputs.

Here is an explanation of why this issue occurs if you're curious:

When parseInt encounters a non-numeric character in the specified radix, it disregards that character and all following ones, returning the integer value parsed up to that point. Leading and trailing spaces are permitted, and numbers are truncated to integers.

Simply setting the radix base to 10 doesn't fully resolve the problem, as demonstrated by @Programmer's scenario with numbers between 0 and 100 still being accepted.

@Pbd's answer also experiences similar issues, coercing strings into numbers without proper validation.

// Without proper validation, this condition allows `1e1` to be stored in an array.
if("1e1" <= 100 && "1e1" >= 0) // evaluates to true!

Due to dynamic typing, the output differs upon summation.

var sum = 0;
sum += totalInputs[i] // assuming totalInputs[i] returns `1e1`
console.log(sum);     // outputs "01e1".

There are various strategies for validating inputs securely, but in my opinion, trimming user input, converting strings to numbers, and validating convertibility into integers is a reliable approach.

userInput = window.prompt("Enter a test score, or 999 to end the program").trim(); // or userInput = userInput.trim();

var convertedInput = +userInput;
var isNumber = convertedInput == userInput; // checking equality "1" == 1
if(userInput && isNumber && convertedInput >= 0 && convertedInput <= 100)
    totalInputs[j] = convertedInput;

To simplify the summation process, consider using reduce.

var sum = totalInputs.reduce(function(pv, cv) { return pv + cv; }, 0);

Alternatively, with arrow functions from ES6, the code becomes even more concise:

var sum = totalInputs.reduce((pv, cv) => pv+cv, 0);

Credit goes to @Chaos's answer. I haven't tested reduce performance across different browsers yet.

Javascript can be quite enjoyable! :)

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

Wondering how to go back to the default locale in Next.js?

Within my Next.js application, I have successfully implemented the next-i18next module for multi-language support. The app currently supports two languages: English and Arabic, with English set as the default. To allow users to toggle between languages, I ...

Adjust the burger menu color based on the background color of the section

Currently, I am working on creating a hamburger menu component with fixed positioning using the 'fixed' property. The menu icon consists of three white lines by default, but I want them to change to black when placed in a white section. I have tr ...

Undefined data is frequently encountered when working with Node.js, Express, and Mongoose

Having a beginner's issue: I'm attempting to use the "cover" property to delete a file associated with that collection, but the problem is that it keeps showing up as "undefined". Has anyone else encountered this problem before? Thank you in adv ...

JavaScript function implemented to add query parameters to HTTP requests

While reviewing my Google Analytics data, I noticed some recurring requests with a script in the query parameter. The format looks something like this: /about?RaNDMPRMz='-function(){debugger}()-">\"><scrIpt>debugger</scrIpt>< ...

Utilize JavaScript's $.Map() function in combination with Math.Max.Apply() to determine the tallest height possible

This code snippet demonstrates how to find the maximum height using jQuery. The $.fn. syntax is utilized to add this method as a jQuery Plugin. $.Map() creates a new array. Math.Max.Apply retrieves the max number from an array. $.fn.t ...

Declaring a variable with global accessibility throughout the React application

Currently, I am working on implementing a Dark Mode feature in React. To achieve this, I am looking to create a central "mega-variable" that can be accessed across the component tree. This variable should appear as: let darkMode = false Once this variabl ...

The Google Apps spreadsheet script occasionally fails to complete iteration but functions properly in all other aspects

I have a script that goes through a spreadsheet of student data one row at a time to email students and their parents if the student's grade is below 60. The spreadsheet columns include: Student ID, Name, Email Address, Parent's Email Address, an ...

Reversing text in mongodb

https://i.sstatic.net/Y61ML.png In my node.js and MongoDB 5 project, I am attempting to retrieve data where the field "TOTAL DUE" has a value other than '$0.00'. I have successfully selected records where "TOTAL DUE" equals '$0.00' usi ...

Converting JSON into HTML has me completely baffled

Despite my best efforts, I have managed to navigate my way through the code thus far, but I am puzzled as to why the JSON data is not being sent to the HTML via JavaScript. I can manually input the necessary parts in the developer console after onLoad an ...

Obtaining the same values from two arrays with distinct structures and indices in Python

I have two arrays with different structures. One array contains more lines than the other: first_array ['1', 'ASUS N56', '1', 'K0AK2M1A', '223422', '0828384'] ['2', 'LG Flatron&ap ...

The error message "Unexpected style type encountered while loading model in ifc.js" was displayed

When I try to load IFC files using the ifc.js library, I frequently encounter numerous messages like the following in the console: Unexpected style type: 3800577675 at 213152 (web-ifc-api.js: 933) Unexpected style type: 3800577675 at 213511 (web-ifc-api.js ...

Inquire about a linq query to efficiently manipulate multiple arrays within an array

I need assistance with converting the elements in an array using Linq. {Mark=90, Students={"Tom","Marry","Jack"}}, {Mark=50, Students={"Niko","Gary","David"}}, {Mark=70, Students={"John","Andy","Amy"}} Is there a way to transform them into individual obj ...

What is the best way to extract the innerHTML of every button and exhibit it in a text box?

How can I create a simpler JavaScript code for clicking buttons to input letters into a text box? Instead of creating getElementByID for each button, is it possible to use some kind of loop? <div id="alpha" > <br/> <div align="cente ...

Using Jquery to manipulate arrays based on options selected from a dropdown menu

I am currently working on a feature that suggests tags based on the selected category. This involves using a select box to choose a category and then displaying sub-categories in a list. Here is the current setup: <select id="categorySelect"> < ...

Choose all options within the optgroup group

I am facing an issue with a select element that contains grouped options. My requirement is to be able to select or deselect all options within an optgroup when a specific option is clicked. Furthermore, I need the functionality to allow multiple optgroups ...

Manage the material-ui slider using play and pause buttons in a React JS application

I have a ReactJS project where I am utilizing the continuous slider component from material-ui. My goal is to be able to control the slider's movement by clicking on a play button to start it and stop button to halt it. Below is the code snippet of th ...

Error: Failed to decode audio content due to a DOMException that was caught in the promise

Encountering an issue with the decodeAudioData method while utilizing the Web Audio API for playback in Chrome (works seamlessly in Firefox)- Sending the audio buffer, which has been recorded by the media recorder, back from the server. Server-side wss ...

Show or hide item by clicking outside the div

Looking for a way to use jQuery's slidetoggle to hide the showup class when clicking anywhere outside of the DIV. Any advice is appreciated! Check out this online SAMPLE: http://jsfiddle.net/evGd6/ <div class="click">click me</div> <d ...

Angular Bootstrap Popover will now automatically hide after a short period of time due to the removal of the tt_isOpen variable in ui-bootstrap-tpls-0

I recently attempted to implement the ingenious directive created by runTarm for managing angular-bootstrap-popover-hide-after-few-seconds. While using ui-bootstrap 0.11.0.js presented no issues, transitioning to ui-bootstrap-0.12.0 proved problematic as ...

Using React Native to Store Items in Flatlist via AsyncStorage

My challenge involves displaying/storing a list of items in a flatlist. The issue arises when I save an item and then load it on another screen; there seems to be a repetitive pattern (refer to the screenshot). Additionally, adding a new item results in re ...