how to add array element values with javascript? - javascript

I am NOT talking about adding elements together, but their values to another separate variable.
Like this:
var TOTAL = 0;
for (i=0; i<10; i++){
TOTAL += myArray[i]
}
With this code, TOTAL doesn't add mathematically element values together, but it adds them next to eachother, so if myArr[1] = 10 and myArr[2] = 10 then TOTAL will be 1010 instead of 20.
How should I write what I want ?
Thanks

Sounds like your array elements are Strings, try to convert them to Number when adding:
var total = 0;
for (var i=0; i<10; i++){
total += +myArray[i];
}
Note that I use the unary plus operator (+myArray[i]), this is one common way to make sure you are adding up numbers, not concatenating strings.

A quick way is to use the unary plus operator to make them numeric:
var TOTAL = 0;
for (var i = 0; i < 10; i++)
{
TOTAL += +myArray[i];
}

const myArray = [2, 4, 3];
const total = myArray.reduce(function(a,b){ return +a + +b; });

Make sure your array contains numbers and not string values. You can convert strings to numbers using parseInt(number, base)
var total = 0;
for(i=0; i<myArray.length; i++){
var number = parseInt(myArray[i], 10);
total += number;
}

Use parseInt or parseFloat (for floating point)
var total = 0;
for (i=0; i<10; i++)
total+=parseInt(myArray[i]);

Related

how to sum integer from htmlelement

I am trying to get the innerHTML of all elements with classname "money" and sum it. But when I am retrieving it with my code it will place all the digits next to eachother.
var elements = document.getElementsByClassName("money");
var arr = new Array(elements.length);
var total = 0;
for (var i=0; i< arr.length; i++){
var val = elements[i].innerHTML;
console.log(val);
total += parseFloat(val).toFixed(2)
}
console.log(total);
The result I'm getting is the following:
image of result
How can I solve this?
toFixed() is converting a number to a string. So you add strings which leads to concatenating.
Sum everything and use toFixed() after you have the final value or use Math.round()
toFixed() returns a string. Parse it (with a unary plus operator), then add to total:
var elements = document.getElementsByClassName("money");
var arr = new Array(elements.length);
var total = 0;
for (var i = 0; i < arr.length; i++) {
var val = elements[i].innerHTML;
console.log(val);
total += +parseFloat(val).toFixed(2)
}
console.log(total);
<div class="money">100</div>
<div class="money">200</div>
<div class="money">300</div>

Javascript How To Concatenate Separate Characters Into One String In Array?

I wrote a code for a "Heads or Tails" game below and:
var userInput = prompt("Enter maximum number output: ");
function coinFlip() {
return (Math.floor(Math.random() * 2) === 0) ? 'Heads' ; 'Tails';
}
for (var i = 0; i < 6; i++)
{
var result = [];
result["randomNum"] = (Math.floor(Math.random()*userInput);
result["coin"] = (coinFlip());
}
I'm trying to count the sum of total heads and sum of total tails each with the code:
var headsCount = 0;
var tailsCount = 0;
for (var j = 0; j < result["coin"].length; j++)
{
if (result["coin"] == 'Heads')
headsCount++;
else
tailsCount++;
}
The only problem is that it's counting each characters of 'Heads' and 'Tails' in the result["coin"] array as separate (such as 'H'-'e'-'a'-'d'-'s') and not into a full string (like "Heads"). Thus, instead of increment by 1 each time the loop above runs, it increments by +5.
I want it to increment by +1 only.
How do I make it so that the code reads the full string stored in result["coin"] and not character-by-character?
EDITED -- changed the <2 to *2
var result = []; is inside the for loop, so it is being overwritten with an empty array each time. So when you try to loop over the results, there's one one item in it; the last one. Pull the result array out of the loop so that you can add to it in each iteration.
It seems userInput should be the number of times to loop. Not sure why you're putting it in result["randomNum"]. result is an array, not an object, so it only has integer keys.
Instead of adding the result of the coin toss to result["coin"] I think you mean to add it to the array, so after tossing it six times it might look like this: ["Heads", "Heads", "Tails", "Heads", "Tails", "Tails"]. You can do this by calling result.push with the coin toss output.
To get one of two results randomly, compare the output of Math.random() against 0.5, which is half way between the limits. Numbers less than 0.5 can be considered heads, while numbers greater than or equal to 0.5 can be considered tails.
Putting it all together, this is what I think you were going for:
function coinFlip() {
return Math.random() < 0.5 ? 'Heads' : 'Tails';
}
var result = [];
var userInput = parseInt(prompt("Enter maximum number output: "), 10);
for (var i = 0; i < userInput; i++) {
result.push(coinFlip());
}
var headsCount = 0;
var tailsCount = 0;
for (var j = 0; j < result.length; j++) {
if (result[j] == 'Heads')
headsCount++;
else
tailsCount++;
}
console.log(headsCount, "heads and", tailsCount, "tails");
All that being said, there are definitely areas for improvement. You don't need to loop once to build the results, then loop a second time to read the results.
You can count the number of heads/tails as the coins are flipped. For example:
function isCoinFlipHeads() {
return Math.random() < 0.5;
}
var numFlips = parseInt(prompt("How many flips?"), 10);
var heads = 0;
var tails = 0;
for (var i = 0; i < numFlips; i++) {
isCoinFlipHeads() ? heads++ : tails++;
}
console.log(heads, "heads and", tails, "tails");

Finding Products within large Digits

I have been working on a way to find products of 5 digits within a large number. For example, I have the number 158293846502992387489496092739449602783 And I want to take the first 5 digits (1,5,8,2,9) and multiply them, then the second, (5,8,2,9,3), multiply then, then the third... And so on. Then I want to find the largest of all of them I find, now I came up with the following code to solve this problem:
// I put the digit into a string so I can modify certain parts.
var digit = "158293846502992387489496092739449602783";
var digitLength = digit.length;
var max = 0;
var tempHolder;
var tempDigit = 0;
var tempArray = [];
for(var i = 0; i<=digitLength; i++){
tempHolder = digit.substring(i, i+5);
tempArray = tempHolder.split("");
for(var j = 0; j < 5; j++){
tempDigit += tempArray[j];
}
if(tempDigit > max){
max = tempDigit;
}
}
console.log(max);
It logs to the console A longer number than what I put into it, along with 10 undefined, no spaces. Can anyone figure out the problem here?

JavaScript Array- adding the values together

I'm trying to take numbers inputted by a user. Store those number inside an array and then add up all values inside the array to get a total number. I'm using numbers 1 -7 to test.
I print the output of the array and I get:
1,2,3,4,5,6,7
returned so it seems that storing the data in an array is working. However when I try to add the values inside the array I get:
01234567
Which makes it look like the function is just pushing the numbers together. I feel like I'm missing something really obvious here but I can't figure out what it is. Any help would be appreciated.
var again = "no";
var SIZE = 7;
var pints = [];
var totalPints = 0;
var averagePints = 0;
var highPints = 0;
var lowPints = 0;
getPints(pints[SIZE]);
getTotal(pints[SIZE]);
println(pints);
println(totalPints);
function getPints()
{
counter = 0;
while (counter < 7)
{
pints[counter] = prompt("Enter the number of pints");
counter = counter + 1;
}
}
function getTotal()
{
counter = 0;
totalPints = 0
for (var counter = 0; counter < 7; counter++)
{
totalPints += pints[counter]
}
}
You can use parseInt to convert the pints values like this
totalPints += parseInt(pints[counter], 10);
And you don't have to hardcode the length like this
for (var counter = 0; counter < 7; counter++)
instead you can use pints.length like this
for (var counter = 0; counter < pints.length; counter++)
Your array contains the strings instead of their integer values, instead of
totalPints += pints[counter];
Try using something like this -
totalPints += parseInt(pints[counter], 10);
That happens since each number is read as a string, not a number. Change:
pints[counter] = prompt("Enter the number of pints");
to:
pints[counter] = +prompt("Enter the number of pints");
to convert the value to a Number so that you get addition instead of concatenation from the + operator.
["1", "2", "3", "4", "5", "6", "7"]
01234567
This is the output produced by your code. Note that values in the array are in quotes, so that means their type is String. When using + with strings you get string concatenation.
That's why you have to convert them to a number.
There are multiple ways to do so.
-> parseInt("5")
-> 5
-> "5" * 1
-> 5
-> Number("5")
-> 5
Change
totalPints += pints[counter]
to
totalPints += parseInt(pints[counter])
parseInt will convert the string values to integers.

How do I add values of a prompt together?

I'm supposed to prompt the user to enter a string of numbers separated by spaces and alert the sum of those numbers. I'm trying to get the values into an array and then add them up, but it's not working. I've tried a ton of different ways. Help please!
var input = prompt("Enter a string of numbers separated by spaces");
var numbers = new Array (input.split(" "));
var sum = 0;
for(var i = 0; i < numbers.length; i++){
sum += numbers[i];
};
alert(sum);
JSFiddle: http://jsfiddle.net/mUqfX/2/
You're close, 2 issues with your code. First, .split returns an array so you don't need to wrap a new around it. Second, you need to parse the number otherwise your joining strings together. Try
var input = prompt("Enter a string of numbers separated by spaces");
var numbers = input.split(" ");
var sum = 0;
for(var i = 0; i < numbers.length; i++){
sum += parseInt(numbers[i]);
};
alert(sum);
You have 2 problems:
input.split(" ") returnss an array, so you don't need to place it in another array
Your numbers array contains strings, which you need to coerce to numbers to total them.
Try this:
var input = prompt("Enter a string of numbers separated by spaces");
var numbers = input.split(" ");
var sum = 0;
for(var i = 0; i < numbers.length; i++){
sum += parseInt(numbers[i]);
};
alert(sum);

Categories

Resources