Summing array on Javascript - javascript

Hi I am trying to sum an array on Javascript with the following codes.
var data[]:
var total=0;
data.push[x]; // x is numbers which are produced dynamically.
for(var i=0, n=data.length; i < n; i++)
{
total=total+data[i];
}
alert(total)
for example if x values are are respectively 5,11,16,7. It shows the total value as 511167 not sum the values 5+11+16+7=39
Do you have any idea why it results like that?
Thanks.

Use parseInt() function javascript
total=parseInt(total)+parseInt(data[i]);

Try with parseInt:
total=total+parseInt(data[i]);

Simply whip a unary + before data[i] to convert the string values to numeric values:
total = total + (+data[i]);
Even better, use += instead of total=total+...:
total += +data[i];
JSFiddle demo.

Try this one:
var total = 0;
for (var i = 0; i < someArray.length; i++) {
total += someArray[i] << 0;
}

Use parseInt() javascript function....
total = total + parseInt(data[i]);
This looks the 'x' which you mention come dynamically has a string type. Just check the "typeof x".

Related

Javascript calculating in for loops

I have a <p id="rabbits">1 2 9 4</p>' And i'm trying to calculate all the 1,2,9,4
However, I'm stuck at this part:
var rabbits = $('#rabbits').text()
var rabbits_array = rabbits.split(/(\s+)/);
for (i in rabbits_array) {
console.log(i) // prints 1,2,9,4
}
How do add all of these numbers together (which is 16 if you count manually) in javascript?
Can map array to number and use reduce
var rabbits = $('#rabbits').text()
var total = rabbits.split(" ").map(Number).reduce((a,c) => a + c)
console.log(total)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="rabbits">1 2 9 4</p>
There are a variety of ways to do this.
var rabbits = $('#rabbits').text()
var rabbits_array = rabbits.split(/(\s+)/);
var total = 0;
rabbits_array.forEach(function(element) {
total += element * 1;
});
console.log(total);
You could use a standard for loop:
for (var i = 0; i < rabbits_array.length;i++) {
total += rabbits_array[i] * 1;
}
You could replace the "multiply by 1" (which would have to validate beforehand that it's actually a number and not a letter), with parseInt or parseFloat. Using these methods can do some of this validation for you, but may also give you odd results.
total += parseFloat(rabbits_array[i]);
https://www.w3schools.com/jsref/jsref_parseint.asp
There are other ways to do this as well, but these are just a few examples to get you going. I'd suggest Googling "javascript loops" to read more about this kind of thing.
Try this:
var rabbits = $('#rabbits').text()
var rabbits_array = rabbits.split(" ");
var total = 0;
for (var i = 0; i < rabbits_array.length; i++) {
total = total + parseInt(rabbits_array[i]);
}
console.log(total)
You need to convert the string version of the number (from your split function) to an actual number before adding them together

while loop doesn't stop in js

I want to use function with while to print only 10 numbers starting from the number I choose.
But while loop doesn't stop looping.
id = prompt('Write any number.');
function numbering(a) {
var i = a;
var j = a + 10;
while (i < j) {
document.write(i);
i++;
}
};
numbering(id);
Try this:
var id = parseInt(prompt('Write any number.'), 10);
In your example id will be of type string and the comparisons won't work as you expect.
When you use function numbering(a) {, the variable a is passed as string.
This results in i and j being set as string.
Taking example:
Suppose you pass 2 as input, your variables will be set as a="2", i="2" and j="210". So according to your condition, it'll print starting from 2 till 209.
You can change your code to parse a as number to achieve your result; something like:
function numbering(a) {
a = parseInt(a); //parse as Int here
var i=a; var j=a+10;
while (i < j)
{
document.write(i);
i++;
}
};
Try it with a for-loop:
for(var i=0; i<10; i++){ doSomething}
You can try with this for-loop function :
id=prompt('Write any number.');
function numbering(a) {
for (let i = a; i < a + 10; i++){
document.write(i);
}
};
numbering(id);
You can add a parseInt(id) to you numbering function parameter call if you want to parse the input into a number
When you enter a number in the prompt, it is supplied as a string. Since you have not converted this into a number, the line var j = a + 10 is actually joining the two values as if they were strings.
For example, if you enter "5" into the prompt, then var j = "5" + 10 returns "510". Only when you then compare the two variables in the while loop with i < j does it get interpreted as a number, and will loop from 5 to 510.
The easiest way to convert a string into a number is to use parseInt(value).
The prompt function returns a string.
The problem is that you are concatenating a string with the number 10.
If you write your variables to document, you can see the problem:
id=prompt('Write any number.');
function numbering(a) {
var i=a; var j=a+10;
document.write(i);
document.write("<br/>");
document.write(j);
document.write("<br/>");
//while (i < j){
// document.write(i);
// i++;
//}
};
numbering(id);
This will fix your problem:
var id=parseInt(prompt('Write any number.'));
you need the parseInt function because what you getting from promt is string. For example 5 +10 . For javascript , it will be 510 .
id=prompt('Write any number.');
function numbering(a) {
var i=parseInt(a); var j=parseInt(a)+10;
while (i < j){
document.write(i);i++;
}};
numbering(id);
document.write(i +"<br>");
In console i am getting proper result. just add line break to see whole result in viewport

Using only one loop to generate nested arrays

I am trying to come up with an algorithm to generate a nested array of consecutive numbers using only one loop. I feel it should be solved somehow using remainder operator but can't quite come up with a general solution. Anyone has any suggestion or hints?
input: 4
output: 1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4
You would use the modulo operator (%), but note that you should loop from zero and up, and the result from modulo is also from zero and up, so you have to add one to it.
var input = 4;
for (var i = 0; i < input * input; i++) {
var n = (i % input) + 1;
document.write(n + '<br>');
}
Something like that should do the trick:
int input = ...
int i = 0;
while(i<=(input*input)){
int output = (i % input) + 1;
i++;
}

Trying to add up an array, but result returns NaN

So I have a string called hoursString that looks like
4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|
I split the string into an array and what I am trying to do is add up all the numbers and return it to the html page in the div "test".
JAVASCRIPT:
var hours=hoursString.split("|");
var total=0;
for (var i=0;i<hours.length;i++)
{
total += hours[i];
}
document.getElementById("test").innerHTML=total;
The result is NaN. Can someone tell me what I am doing wrong?
Thanks!
4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|
remove the last |, split will otherwise add an empty string at the end of the array which will give NaN and NaN + number evaluates to NaN
edit: and yes, parseFloat is necessary too, otherwise the result will be a string instead of NaN
var hoursString = "4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|",
hours = hoursString.split("|"),
total = 0;
for (var i = 0; i < hours.length; i++) {
total += parseFloat(hours[i]) || 0; // see explanation
}
document.getElementById("test").innerHTML = total;
Why the || 0? Because it checks if the string is "", if so the || operand will return the second value, in this case 0.
This will output 25.740000000000002. See this answer on the cause of the "wrong" result, and here is a working fiddle.
Your issue is that each element in hours is still a string value even though it is written as a number. The easiest way to fix this would be to use javascripts parseFloat() function.
Example:
var hours=hoursString.split("|");
var total=0;
for (var i=0;i<hours.length;i++)
{
total += parseFloat(hours[i]);
}
document.getElementById("test").innerHTML=total;
EDIT: Changed from parseInt to parseFloat
var hoursString = "4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|"
var hours=hoursString.split("|");
var total=0;
var idx = 0;
for(idx in hours) {
total += +hours[idx];
}
alert(total);
FIDDLE

Javascript to add the numbers delimited by comma

I am trying to get the sum of all the integers whithin a text box. The numbers are separated by comma. I need to add the numbers and get their sum.I am not able to get them sadly.
my code is :
<script type="text/javascript">
function computeData()
{
var data = document.getElementById("data").value;
var temp = data.split(",");
for( i=0; i<temp.length; i++)
var k=0;
{
var j = temp[i];
k = k + j;
alert(k);
}
document.getElementById("sum").value= k;
}
</script>
You need to parse your strings into integers using parseInt:
> 2 + '3'
'23'
> 2 + parseInt('3', 10)
5
The 10 tells parseInt to assume that the number is base-10. If you have floating point numbers, use parseFloat() (you don't need to specify a radix):
> 2 + parseFloat('3.13')
5.13
If you know they'll be integers:
var data = document.getElementById("data").value;
var sum = data.split(",").reduce(function(prev, curr){
return parseInt(prev,10) + parseInt(curr,10);
});
If you aren't sure about integers you can use parseFloat in place of the parseInt.
Note that this may not work in older browsers. If you need to support IE older than IE9, you probably just want to use parseInt/parseFloat in your loop as is. (with the k declaration moved outside the loop)
var k=0;
for( i=0; i<temp.length; i++)
{
var j = temp[i];
k = k + parseInt(j,10);
alert(k);
}
This could work on a CSV string of integers or floats.
var data = document.getElementById("data").value;
var a = data.match(/\d+(?:[.]\d+)?/g);
var num = 0;
a.forEach(function(n){
num += parseFloat(n);
});
console.log(num);
I might also suggest the following syntax
var temp = data.split(",");
for(var i=0, k=0; i<temp.length; i++;)
{
k += parseInt(temp[i]);
}
I like the eval idea, but you can also use a regular expression to match and total the integers and decimals, and any plus or minus signs. Non numbers are ignored, so you can delimit with commas or spaces, or just use '+' or '-' between numbers.
function computeData(){
var data= document.getElementById("data").value;
var rx=/([+-]?(\.\d+|\d+(\.\d+)?))/g, n= 0, M;
while((M= rx.exec(data))!= null){
n+= (+M[1])
}
document.getElementById("sum").value= n;
}
Consider:
var data = '1,2,3';
eval(data.split(',').join('+'))); // 6
or
eval(data.replace(/,/g,'+')); // 6
Edit
For all those eval haters out there (you know who you are!!):
var sum = data.split(',').reduce(function(p, c){return p + +c},0);
Note that support for ES5 reduce is required, there's a polyfill on MDN.

Categories