JavaScript for-loop question - javascript

Is it possible for a for-loop to repeat a number 3 times? For instance,
for (i=0;i<=5;i++)
creates this: 1,2,3,4,5.
I want to create a loop that does this: 1,1,1,2,2,2,3,3,3,4,4,4,5,5,5
Is that possible?

for (i=1;i<=5;i++)
for(j = 1;j<=3;j++)
print i;

Yes, just wrap your loop in another one:
for (i = 1; i <= 5; i++) {
for (lc = 0; lc < 3; lc++) {
print(i);
}
}
(Your original code says you want 1-5, but you start at 0. My example starts at 1)

You can have two variables in the for loop and increase i only when j is a multiple of 3:
for (i=1, j=0; i <= 5; i = ++j % 3 != 0 ? i : i + 1)

Definitely. You can nest for loops:
for (var i = 1; i < 6; ++i) {
for(var j = 0; j < 3; ++j) {
print(i);
}
}
Note that the code in your question will print 0, 1, 2, 3, 4, 5, not 1, 2, 3, 4, 5. I have fixed that to match your description in my answer.

Just add a second loop nested in the first:
for (i = 0; i <= 5; i++)
for (j = 0; j < 3; j++)
// do something with i

You can use nested for loops
for (var i=0;i<5; i++) {
for (var j=0; j<3; j++) {
// output i here
}
}

You can use two variables in the loop:
for (var i=1, j=0; i<6; j++, i+=j==3?1:0, j%=3) alert(i);
However, it's not so obvious by looking at the code what it does. You might be better off simply nesting a loop inside another:
for (var i=1; i<6; i++) for (var j=0; j<3; j++) alert(i);

I see lots of answers with nested loops (obviously the nicest and most understandable solution), and then some answers with one loop and two variables, although surprisingly nobody proposed a single loop and a single variable. So just for the exercise:
for(var i=0; i<5*3; ++i)
print( Math.floor(i/3)+1 );

You could use a second variable if you really only wanted one loop, like:
for(var i = 0, j = 0; i <= 5; i = Math.floor(++j / 3)) {
// whatever
}
Although, depending on the reason you want this, there's probably a better way.

Related

Can I create a counter that outputs the following counters

I need a 2 counter, i & j that output the following counters for each iteratation:
0,1,2,3,4,1,2,3,4,2,3,4,3,4
Counter variable sequence to achieve the above when output to console.log is as follows:
i,j,j,j,j,i,j,j,j,i,j,j,i,j
With each iteration, when i increments, j must start it's incrementation at i + 1 and must complete it's loop for each incrementation of i.
Each counter value will be used to present option from an array for comparison with one another.
I've tried using a nested for loop and it has not worked. I am also calling a function containing the second loop with some success but want to know if there is a more elegant way to accomplish this.
function createValues() {
for (i = 0; i < 9; i++) {
var counter_i = i;
decreasingLoop(counter_i);
}
}
var k = 1; // counter for inner values loop
function decreasingLoop(get_i) {
for (j = k; j < 10; j++) {
// functions using the counters are entered here.
if (j == 9) { // increments k so that the next time the counter runs it starts at +1 from previous iteration)
k++;
}
}
j = k;
}
I am getting the desired results but want to know if there is a simpler way to achieve the desired outcome.
for(var i = 0; i< 4; i++){
console.log(i)
for(var j = i+1; j<= 4; j++){
console.log(j)
}
}
If you write out your desired output in a different format, the solution may become a little clearer:
i: 0
j: 1,2,3,4
i: 1
j: 2,3,4
i: 2
j: 3,4
i: 3
j: 4
As you can see from the above example, i increases linearly, and only takes the values of 0 through to 3. Each time i takes a new value, j loops from i+1 up to 4. Using this idea, you can create an outer for loop for i (which loops from 0 to 3) and an inner for loop for j which starts at i+1 and finished when j is equal to 4:
for(let i = 0; i <= 3; i++) {
console.log(i);
for(let j = i+1; j <= 4; j++) {
console.log(j);
}
}
Try following nested loop - notice that in second loop initial for value is j=i+1
let n=4, m=5;
for(let i=0; i<n; i++) for(let j=i+1; j<m; j++) {
console.log({i,j});
}

Javascript : Omitted Initialize inside Nested For Loop

As we know, we can omit the initialization inside the for loop :
var i = 0;
for(; i < 10; i++) {
// do Something with i
}
However, i figure out if i omit the initialization inside the nested loop as well:
var i = 0;
var j = 0;
for(; i < 10; i++) {
for(; j < 10; j++) {
// only do Something with j
// outner loop only run once
}
}
Solution :
var i = 0;
var j;
for(; i < 10; i++) {
j = 0;
for(; j < 10; j++) {
// everything is fine!
}
}
Can anyone explain whats going on? I'm newbie in Javascript.
The loop runs multiple times, but your 'j' is already ten after the first run of i, so the second loop no longer runs during the next values of i.
If you would write something like this.
for(; i < 10; i++) {
for(; j < 10; j++) {
console.log("test")
}
console.log("another test")
}
You would see that both messages get printed 10 times.
The reason that your "j" loop, only runs "ten times once", is because you do not set J back to zero after it has run 10 times. So the statement j < 10is true for every loop if iafter the first run.
You could solve this by setting j = 0 inside the first for loop (if you do not want to put it inside the variable initialisation of the second loop.)
for(; i < 10; i++) {
j = 0;
for(; j < 10; j++) {
console.log("test")
}
console.log("another test")
}
Every time i increments, you need to reset j to 0.
If you rewrite your script so that each variable is initialised within the for loop statement itself, then every time i increments, j will be reset to 0.
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
}
}

Referencing Javascript array element via loop variable

I've come across writing a piece of code where I wanted to reference the 2D array d2_arr[][] in a loop like so.
for (var i=0; i<d2_arr[i].length; i++) {
//do something
}
Google Script compiler throws an error "cannot read length property from undefined". When I changed [i] for [1], it worked just fine. Could anyone please explain why this is wrong? And a related question: Can a 2D array have a different number of elements in a row? theoretically. An example would be:
[[1,2],[3,4,5],[6,7,8,9],[10,11]]
EDIT. Full code part.
var ids = [];
var j = 0;
for (var i=0; i<d2_arr[i].length; i++){
if (d2_arr[i][2]<=0.05){
ids[j]=d2_arr[i][0];
j++;
}
}
I understood the mistake. Thank you!
You typically need a nested for loop to traverse a 2-D array
var d2_arr = [[1,2],[3,4,5],[6,7,8,9],[10,11]]
for (var i=0; i<d2_arr.length; i++){
for (var j=0; j<d2_arr[i].length; j++){
console.log(d2_arr[i][j] + ' ')
}
}
It is perfectly fine for arrays to be "jagged" and contain uneven sized arrays in the main array.
Here is a fiddle http://jsfiddle.net/7Lr4542s/
Arrays in JS can be of any size and any type. You can combine number and strings in array.
var twoDArray = [[1], ["one", "two"], ["i", "ii", "iii"]];
for(var i = 0; i < twoDArray.length; i++) {
for(var j = 0; j < twoDArray[i].length; j++) {
print(twoDArray[i][j]);
}
}
var threeDArray = [[["1.1.1", "1.1.2"], ["1.2.1", "1.2.2"]], [["1.2.1", "1.2.2"], ["1.2.1", "1.2.2"]], [["2.1.1", "2.1.2"], ["2.2.1", "2.2.2"]], [["2.2.1", "2.2.2"], ["2.2.1", "2.2.2"]]];
for(var i = 0; i < threeDArray.length; i++) {
for(var j = 0; j < threeDArray[i].length; j++) {
for(var k = 0; k < threeDArray[i][j].length; k++) {
print(twoDArray[i][j][k]);
}
}
}

Find if Array contains a user

I have a parse background job that contains a simple query.each for one class. This class has 2 Arrays field filled with objects.IDs. Inside this query, for every single object, i need to check if the objects.ID of the first Array are contained in the second Array.
Basically in a simple loop:
var j = 0;
for (var j = 0; j < firstArray.length; j++) {
if(firstArray[j] "isContainedIn" secondArray){
// my custom code
}
}
What i can't figure out is the function to use, if exist..Does javascript have a function like that or i need to make a nested loop to achieve my goal?
EDIT: i worked it out using indexOf but the solution proposed by Shqiptar didn't work so here is the one that actually works:
first Array name = usersEligibleToVote
second Array name = usersThatVoted
for (var j = 0; j < usersEligibleToVote.length; j++) {
if(usersThatVoted.indexOf(usersEligibleToVote[j]) === -1){
console.log("user.id "+usersEligibleToVote[j]+" needs to vote");
} else {
console.log("user.id "+usersEligibleToVote[j]+" has voted");
}
}
var j = 0;
for (var j = 0; j < firstArray.length; j++) {
if(firstArray[j].contains(secondArray))
{
// your custom code here
}
}
And then for checking if an object is the same :
var j = 0;
for (var j = 0; j < firstArray.length; j++) {
if(firstArray[j].indexOf(secondArray) != -1)
{
// your custom code here
}
}
I would process it through a simple jQuery and javascript for loop like so:
var arr1;
var arr2;
var i;
for(i = 0; i < arr1.length; i++) {
if ($.inArray(arr1[i], arr2) {
break; //do things here or what not
}
}

Why is iterating through an array backwards faster than forwards

Given this code:
var arr = [];
for (var i = 0; i < 10000; ++i)
arr.push(1);
Forwards
for (var i = 0; i < arr.length; ++i) {}
Backwards
for (var i = arr.length - 1; i >= 0; --i) {}
Hard-coded Forward
for (var i = 0; i < 10000; ++i) {}
Why is backwards so much faster?
Here is the test:
http://jsperf.com/array-iteration-direction
Because your forwards-condition has to receive the length property of your array each time, whilst the other condition only has to check for "greater then zero", a very fast task.
When your array length doesn't change during the loop, and you really look at ns-perfomance, you can use
for (var i=0, l=arr.length; i<l; i++)
BTW: Instead of for (var i = arr.length; i > 0; --i) you might use for (var i = arr.length; i-- > 0; ) which really runs through your array from n-1 to 0, not from n to 1.
Because in the first form you are accessing the property length of the array arr once for every iteration, whereas in the second you only do it once.
If you want to have them at same pace, you can do that for forward iteration;
for(var i=0, c=arr.length; i<c; i++){
}
So, your script won't need to take length of array on everystep.
I am not entirely sure about this, but here is my guess:
For the following code:
for (var i = 0; i < arr.length; ++i) {;
}
During runtime, there is an arr.length calculation after each loop pass. This may be a trivial operation when it stands alone, but may have an impact when it comes to multiple/huge arrays. Can you try the following:
var numItems = arr.length;
for(var i=0; i< numItems; ++i)
{
}
In the above code, we compute the array length just once, and operate with that computed number, rather than performing the length computation over and over again.
Again, just putting my thoughts out here. Interesting observation indeed!
i > 0 is faster than i < arr.length and is occurring on each iteration of the loop.
You can mitigate the difference with this:
for (var i = 0, len = arr.length; i < len; ++i) {;
}
This is still not as fast as the backwards item, but faster than your forward option.
do it like below, it will perform in same way. because arr.length takes time in each iteration in forward.
int len = arr.length;
forward
for (var i = 0; i < len; ++i) {
}
backward
for (var i = len; i > 0; --i) {
}
And these are equally good:
var arr= [], L= 10000;
while(L>-1) arr[L]= L--;
OR
var arr= [], i= 0;
while(i<10001) arr[i]=i++;

Categories

Resources