How do I get a sum of these numbers in array? - javascript

I want to use for. There are two things, one, the console.log doesn't work inside the for statement. Second, it is not summing up. code below:
var numbers = [1,2,3,4];
var total = 0;
for (var i= 0; numbers.length < i; i++){
total += numbers[i];
// console.log(total); doesn't work
}
// console.log(total); gives 0

Change condition in for should be i < numbers.length not numbers.length < i
var numbers = [1,2,3,4];
var total = 0;
for (var i= 0; i < numbers.length; i++){
total += numbers[i];
}
console.log(total);

Your for loop is exiting immediately because of the condition
for (var i = 0; numbers.length < i; i++) {
Because numbers.length (in this case) is 4, and i is 0, the for loop never executes.
You probably want it flipped around, to say something like
for (var i = 0; i < numbers.length; i++) {

Related

Adding different number of '-' in every loop (javascript)

I need to create a string like this: 01-2--3---4----5-----6------7------- for a let n=7, using a loop.
I've created something like this so far:
let numbers = '';
n = 7;
for(i=0; i<=n; i++) {
numbers += i;
if (i>0) {
numbers += ('-')
}}
which gives me: "01-2-3-4-5-6-7-". Don't know how to change the code so that it could multiply the number of '-' equal n in every loop.
What you need is a nested loop, to iterate over the value of i in the outer loop.
const n = 7
let result=''
for (let i = 0; i <= n; i++) {
let dashes=''
for(let j=0; j < i; j++){
dashes+='-'
}
result+= `${i}${dashes}`
}
console.log(result)
You could use String#repeat for the wanted dash.
Do not forget to declare any variable.
let numbers = '',
n = 7;
for (let i = 0; i <= n; i++) numbers += i + '-'.repeat(i);
console.log(numbers);
This the solution for your problem:
var numbers = '';
var n = 7;
for(var i = 0; i <= n; i++) {
numbers += i;
for(var j = 0; j < i; j++) {
numbers += "-";
}
}

How to Count data in for loop nodejs

How to Count data in for loop nodejs
var service_count = 0;
for (let i = 0; i < res.length; i++) {
service_count += i;
console.log('service_charge_count: =====> '+service_count);
}
By adding i to your variable, you're adding in the first loop 0, in the second loop 1, in the third loop 2. So you're not counting anything.
var service_count=0;
for(let i=0;i<res.length;i++){
service_count++;
}
console.log('service_charge_count: =====> '+service_count);
By that you'll see how many iterations has had the loop. If the final value of service_count is the length of the variable res you can do this:
var service_count = res.length;
console.log('service_charge_count: =====> '+service_count);
Replace i with service_count, then you can change your code with:
for(let service_count = 0; service_count < res.length; service_count ++){
console.log('service_charge_count: =====> ' + service_count);
}
Or I think that you service_count is res.length, therefore, you can do:
let service_count = res.length;
console.log(service_count);

JavaScript Scope : please explain me why different result in and of loop creating variable

Can you please explain to my why i get to different results;
This is the finished code and the result I wished:
function largest_of_arrs(arr){
var largest_arr = [];
var holder;
var max = 1;
for(var i = 0; i < arr.length; i++){
var sum = 0;
for(var j = 0; j < arr[i].length; j++){
sum += arr[i][j];
if(sum > max) {
max = sum;
largest_arr = arr[i];
}
}
}
return largest_arr;
}
var array_1 = [[1,2,3,4,5],[1,2,2,3,1],[11,12,23,45,88],[20,20,5,5,1]];
largest_of_arrs(array_1);
This gives me the wished result: [11,12,23,45,88]
But when i declare the sum variable outside the for loop like this
function largest_of_arrs(arr){
var largest_arr = [];
var holder;
var max = 1;
var sum = 0;
for(var i = 0; i < arr.length; i++){
for(var j = 0; j < arr[i].length; j++){
sum += arr[i][j];
if(sum > max) {
max = sum;
largest_arr = arr[i];
}
}
}
return largest_arr;
}
var array_1 = [[1,2,3,4,5],[1,2,2,3,1],[11,12,23,45,88],[20,20,5,5,1]];
largest_of_arrs(array_1);
The result is: [20,20,5,5,1]
Can you please explain to me why ?, and how to scope here works?
if possible please with pictures (graphical) ..
Can you please explain to me why?
In the first case, you reset the value of sum to zero on each iteration of the outer loop. In the second case, you don't so sum just keeps accumulating.
and how to scope here works?
Variables declared with var have function scope (or global if declared globally). Your problem isn't to do with scope, it's because of where you assign 0 to sum.
if possible please with pictures (graphical)
Sorry, no pictures. :-(
First Case -
i=0
sum = 0;
j iterates till end of loop
sum = 1+2+3+4+5;
i=1
sum = 0;
j iterates till end of loop
sum = 1+2+2+3+1;
i=2
sum = 0;
j iterates till end of loop
sum = 11+12+23+45+88;
....
Second Case -
i=0
sum = 0;
j iterates till end of loop
sum = 1+2+3+4+5;
i=1
sum = 1+2+3+4+5;
j iterates till end of loop
sum = (1+2+3+4+5)+1+2+2+3+1;
i=2
sum = ((1+2+3+4+5)+1+2+2+3+1);
j iterates till end of loop
sum = ((1+2+3+4+5)+1+2+2+3+1)+11+12+23+45+88;
...
The for statement does not define a scope in javascript, only functions do (as per ES5).
Your problem is because the moment you assign 0 to sum: inside the outer for.

Can someone please tell me why this code wont run?

var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
for(var i = 0; i <= howM; i++)
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace (/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1)); }
console.log(sum);
It tells me this "TypeError: Cannot read property 'replace' of undefined
at eval:13:11" which makes no sense to me because its right above it.
The intetended body of the loop for(var i = 0; i <= howM; i++) is not enclosed in braces {..}. As a result, only the statement var sum = 0; will be executed in the loop. Also, you probably meant to say i < howM. So you want something like this for the loop:
for(var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace (/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
}
console.log(sum);
Check the comments:
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < parseInt(howM); i++)
arr.push(prompt("Enter a card:")); //No curly braces is fine when its a single line. When there's no braces, JS just runs the next line x amount of times
console.log(arr)
var sum = 0; //Create sum out here. Setting it to zero every loop defeats the purpose
for(var i = 0; i < arr.length; i++)//You said "i <= howM". Better to use the length of the array that is being looped through
{ //Use curly braces to show what code to execute repeatedly
var eXt = arr[i]; //Set eXt to the current number
eXt = eXt.replace("-", ""); //No need for regex
sum += parseInt(eXt); //Convert the input to a number, then add it to sum
}
console.log(sum);
The second for loop doesn't have brackets around it. You can MUST use brackets UNLESS it is a one line loop. For example:
This is fine:
for (var i=0;i<100;i++)
console.log(i);
This is NOT:
for (var i=0;i<100;i++)
var x = i;
x++;
console.log(x);
So the second for loop should be this:
for(var i = 0; i <= howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace (/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
console.log(sum);
}
Also in the first for loop I would use arr[i] = value instead.

How to make a for loop dynamic?

I am have 2 arrays like [2,3] and [1000,1200,500,600,1600] .
I need to write a for loop for this like.
1.start index from 0 and end index at 2.
2.start time from 2 and end index with sum of first 2 element (2+3)= 5.
var arr = [2,3];
for(var i = 0; i<arr.length;i++)
{
//this loop runs 2 time
for(var j = 0 ; j < 2 ; j++)//for the first time
for(var j = 2 ; j < 5 ; j++)//for the second time
}
How to make this dynamic for loop? Can someone please help me code?
This would do what you want and would be extendible.
var arr = [2,3];
var sum = 0;
for(var i = 0; i<arr.length;i++)
{
sum += arr[i]
if (i === 0) {
for(var j = 0 ; j < arr[0] ; j++)
// Do first thing
}
if (i > 0) {
for(var j = arr[0] ; j < sum ; j++)
// Do second thing
}
}
Hope you are expecting this.
var arr = [2, 3];
for (var i = 0; i < arr.length; i++) {
//this loop runs 2 time
if (i == 0) {
//for the first time
for (var j = 0; j < arr[0]; j++) { }
} else if (i == 1) {
//for the second time
var totalSum = arr[0] + arr[1];
for (var j = arr[0]; j < totalSum; j++) //for the second time
{ }
}
}
If you want it to be generic, i.e. you have the array arr containing counts of elements to process, you could do it like this:
var arr = [2,3];
// k is the index into the second array, initialize to 0 here
for(var i = 0, k = 0; i < arr.length;i++)
{
//this loop runs for each element in the arr[] array
for(var j = 0 ; j < i; j++, k++) // increment k
{
// k is now the value you want:
// first time through the loop 0, 1
// second time through the loop 2, 3, 4
}
}
Another tweak would be to just keep track of the start element if it's important for j to be the value:
var arr = [2,3];
var start = 0;
for(var i = 0; i < arr.length; i++)
{
var end = start + arr[i]; // end is 2,5 in sample
for(var j = start ; j < end; j++)
{
// first time through the loop 0, 1
// second time through the loop 2, 3, 4
}
start = end; // now start at the next index, 0,2 in sample
}
Do something like this:
var k = 0;
for(var j = 0 ; j < 2 ; j++) {
k+=arr[j];
}//for the first time
for(var i = 2 ; i < k ; i++) {
//other code
}

Categories

Resources