Javascript calculating in for loops - javascript

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

Related

For loop returning completely wrong value using power function

As you can see int he code below I separate the n variable and convert back to an integer array. When I put these numbers into my for loop they come out in the billions. Any help would be greatly appreciated.
var n = [86]
var p = [1]
n = n.toString().split("").map(function(value) {
return(parseInt(value))
})
var total = 0;
for(i=0;i<n.length;i++) {
total += (Math.pow(n[i],(p+i))
}
console.log(total)
You need the conversion from strings to numbers and you are adding an array to numbers.
You cannot sum an array to an integer [1]+0, it doesn't result in a number. It will do a concatenation.
var n = [86]
var p = [1]
n = n.toString().split("").map(val => Number(val))
var total = 0;
for (i = 0; i < n.length; i++) {
total += Math.pow(n[i], (p[0] + i))
}
console.log(total);
p is an array not an individual number, in your for loop, when it is running (p+i), that value ends up being 10 and 11. So your first loop is running Math.pow(8,10) and the second time it runs it is running Math.pow(6,11), which, will result in a number in the billions

For loop to get the total of all iterations in Javascript, using node.js

I was trying to get the total of iterations in a for loop on Javascript using node.js. Here is my code
var sum = 0;
for (itr=1; itr<=5; itr++) {
var lt = 8;
var sum = sum+lt;
console.log(sum);
}
So what I get here is a list of values as the output. How do I get the last value (the total of all iterations) 40 as a single output. Can someone please guide me through this?
Just move console.log(sum) outside your loop. Like this
var sum = 0;
for (itr=1; itr<=5; itr++) {
var lt = 8;
var sum = sum+lt;
}
console.log(sum);
BTW, two possible improvements:
remove the var in var sum = sum+lt;
make your iteration variable var, like this: for (var itr=1; itr<=5; itr++) {

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++;
}

How to sum up distinct value using javascript

I want to try and sum up distinct value from a list.. currently i am able to do so if theres only 2 similar record. If theres more than 2 i am not able to do the checking. Following is the javascript code:
function validateData(){
var total = document.frm.size.value;
var msg="";
var tbxA;
var tbxB;
var tbxA2;
var tbxB2;
var tbxC;
var totalValue =0;
var repeatedValue= 0;
var row = 0;
var row2 = 0;
for(var i=0; i<parseInt(total); i++){
tbxA = document.getElementById('tbx_A'+i).value;
tbxB = document.getElementById('tbx_B'+i).value-0;
tbxC = document.getElementById('tbx_C'+i).value;
for(var j=i+1; j<parseInt(total); j++){
tbxA2 = document.getElementById('tbx_A'+j).value;
tbxB2 = document.getElementById('tbx_B'+j).value-0;
if (tbxA==tbxA2) {
totalValue = tbxB + tbxB2;
}
if (totalValue != tbxC) {
repeatedValue= 1;
row = i;
row2 = j;
msg+="*total value does not add up at row " +(row2+1);
break;
}
}
if(repeatedValue== 1){
break;
}
}
return msg;
}
For example A:type of fruit, B: total of each fruit, C: how many bought at a time
total of C should be equal to B. i.e Apple: 3+3+4 = 10. So if the total is not equals to 10 it should prompt me an error.
A B C
Apple 10 3
Orange 10 10
Apple - 3
Apple - 4
My code above will prompt error bt it doesnt go beyond 2nd occurence of Apple.
So yes, how should i go about to ensure it loop through the whole list to sum up all similar values?
Thanks in advance for any possible help!
Try this:
var total = +document.frm.size.value,
data = {};
for(var i=0; i<total; ++i) {
var key = document.getElementById('tbx_A'+i).value;
data[key] = data[key] || {B:0, C:0};
data[key].B += +document.getElementById('tbx_B'+i).value || 0;
data[key].C += +document.getElementById('tbx_C'+i).value || 0;
}
for(var i in data) {
if(data.hasOwnProperty(i) && data[i].B != data[i].C) {
return "total value does not add up";
}
}
return "";
Some comments:
parseInt (and parseFloat) is very slow. + operator before string converts it to a number much faster. But if you really want to make sure the numbers are integers, use Math.floor(), Math.round(), Math.ceil() or the faster but illegible |0.
In case you really want parseInt (e.g. you want to convert '123foobar' into 123), always use a radix. For example: parseInt('123', 10)
Avoid doing calculations at the condition of a loop, because they run at each iteration. Just do the calculation once before the loop and save the result in a variable.

find the mean of an array of 1000 random integers javascript

I am having trouble with calculating the mean value of an array of 1000 random numbers. The array holds 1000 random number between 1 and 30.
I also want to be able to count how many of each number occurred in the array and print the amount of each number in a frequency distribution table.
<script type = "text/javascript">
var arr = [];
function getRandom( num ){
return Math.round(Math.random() * num)+1;
}
for (var i = 0; i < 1000; i++) {
arr.push(getRandom( 30 ));
}
document.write(arr);
document.write("<br/>");
for (var i = 0; i <= 1000; i++){
sum += parseInt(arr[i]);
}
var mean = sum/arr.length;
document.write("The sum of all the elements is: " + sum + " The mean is: " + mean);
</script>
You don't have to run the cycle twice. Do everything on the fly:
var distrTable = {};
for (var i = 0; i < 1000; i++) {
var rnd = getRandom(30);
sum += rnd;
arr.push(rnd);
if (!distrTable[rnd]) {
distrTable[rnd] = 0;
}
distrTable[rnd]++;
}
Now the variables contain the following information:
arr - all random numbers.
distrTable - each random number with frequency.
sum - the sum of all random numbers.
jsFiddle example
By the way, if you're wondering why your code is not working... Here are the reasons:
First of define the variable sum. Before the loop just put sum = 0;
Second of all, while the array is long 1000 items, in the second for you loop for 1001 times. The declaration should be as follows:
for (var i = 0; i < 1000; i++) // not i <= 1000;
Then the code should work.
The trivial error in your code is that in your second loop you are running up to element 1001 instead of element 1000.
Since that element is undefined, it causes a sum of NaN and the mean, likewise.
To fix, change the <= 1000 to just < 1000
You should also remove the parseInt call - that's only necessary if your input values are strings, but your array already contains numbers.
Beware when you generate random numbers like this:
function getRandom( num ){
return Math.round(Math.random() * num)+1;
}
... this code can generate numbers from 1 to 31! It's because of the Math.round -- if Math.random() generates 0.99, 0.99 * 30 will equal 29.7, that will be rounded to 30, and then 1 will be added!
The solution is to replace Math.round with Math.floor.

Categories