Suhail Mumtaz Awan
Suhail Mumtaz Awan

Reputation: 3483

How to set more than one limit on for loop : javascript

I am working with javascript arrays, here i am using for loop to get the top three results.(no .length limit)

Attempting to have something like

for(let a=0;a<usss.length || a<3;a++)

Simple

var users = ['s','g','h','i'];
for(let a=0;a<3;a++){//dont want to use a < users.length
   console.log(users[a]);
}

problem

var users2 = ['s','g'];
for(let a=0;a<3;a++){
  console.log(users2[a]);
}

The way around,

var users2 = ['s','g'];
for(let a=0;a<users2.length;a++){
 if(a<3){
  console.log(users2[a]);
 }
}

Real Question

How can i avoid using extra if() condition in my last stated code?

I am sorry if its very basic question, i just stuck on it. Any help or information will be appreciated. Thanks for your time.

Upvotes: 2

Views: 6267

Answers (5)

Gene Parcellano
Gene Parcellano

Reputation: 6044

If you just want the lesser of 2 values as the limit, you can use Math.min().

let users2 = ['s','g'];

for (let a = 0; a < Math.min(users2, 3); a++) {
    console.log(users2[a]);
}

Upvotes: 1

StudioTime
StudioTime

Reputation: 23999

You could use also use Array.some()

Note: Check browser compatibility and/or use polyfill

[1, 2, 3, 4, 5, 6, 7].some((el, idx) => {
  console.log(el);
  return ++idx === 4; /* <-- return top 4 */
});

Upvotes: 1

caramba
caramba

Reputation: 22490

There will be no way without using an if somewhere as you have to check the length of the value.

var users = ['s','g','h','i'];

// define the length value outside
var length = users.length >= 3 ? 3 : users.length;

for(let a=0; a < length; a++){
   console.log(users[a]);
}

var users2 = ['s','g'];
for(let a=0; a < length; a++){
   console.log(users[a]);
}


// you can define it inside the for loop but it's not so nice for reading
for(let a=0; a < (users.length >= 3 ? 3 : users.length); a++){
   console.log(users[a]);
}

Maybe the nicest would be to create a function and pass the 3 as a maxLength parameter

var logMax = function(users, maxLength, info) {
  let length = users.length >= maxLength ? maxLength : users.length;
  for(let a=0; a < length; a++){
    console.log(info, ' => ' + users[a]);
  }
}

var users = ['s','g','h','i'];
logMax(users, 3, 'first');

logMax(['s','g'], 3, 'second');

Upvotes: 1

Rahul khanvani
Rahul khanvani

Reputation: 401

Its very simple, I think you just need to go through the length of the array.

 var users2 = ['s','g'];
for(let a=0;a<users2.length;a++){
  console.log(users2[a]);
}

Upvotes: 0

Esteban
Esteban

Reputation: 1815

This seems to work :

var users = ['s','g','h','i'];

var users2 = ['s','g'];

for(let a=0;(a<3 && a<users.length) ;a++){
   console.log(users[a]);
}

for(let a=0;(a<3 && a<users2.length);a++){
  console.log(users2[a]);
}

Upvotes: 5

Related Questions