Is there a possible way to loop through arrays at a specific range rather than loop through the whole thing?

77 views Asked by At

I'm currently going through array exercises to practice my programming on array iteration. I have an array of string objects inside that look like this.

var balling = [
  "Calvin Klein", "Tommy Hilfiger", "FUBU", "Rocca Wear",
  "Calvin Klein", "Tommy Hilfiger", "FUBU", "Rocca Wear"
];

Now what I know will work is if I come in and loop through all of them like this.

for (var i = 0; i < balling.length; i++) {
  balling[i] = console.log(balling[i]);
};

and then the whole thing prints out one by one, top to bottom.

What I would rather do is instead of all 8 of the objects inside that array printing out, I want the for to specify a specific range of objects inside my array.

What exactly do I have to do for my for loop to get the result I want? Is there a way for me to specify how many objects in my array get printed out? Not just one but two, three, and a starting place to start the array and a set range?

4

There are 4 answers

0
Marlus Araujo On

You can use Math.min(a,b) function, that gets the lowest value from a or b, so if the array length is smaller than the number of entries you want to get as minimal, you will not have a problem:

var min_entries = 4;

for (var i = 0; i < Math.min(balling.length, min_entries); i++) {
  balling[i] = console.log(balling[i]);
};

If you want a differente range, you can also use Array.prototype.slice method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice?v=example

var a = ['zero', 'one', 'two', 'three'];
var sliced = a.slice(1, 3);

console.log(a);      // ['zero', 'one', 'two', 'three']
console.log(sliced); // ['one', 'two']
0
guest271314 On

You can create an array having elements reflecting the range of indexes which should be iterated within a for loop. Increment the first element of range until second element of range is reached.

var balling = ["Calvin Klein", "Tommy Hilfiger", "FUBU", "Rocca Wear"
              , "Calvin Klein", "Tommy Hilfiger", "FUBU", "Rocca Wear"];

var [from, to] = [2, 5];

for (; from < to; from++) console.log(balling[from]);

0
Christian Esperar On

You can change declare a var for start and range that will define how many will show eg:

var start = 1;
var range = 4;

for (var i = start; i < start + range; i++) {
  balling[i] = console.log(balling[i]);
};
0
jsw324 On

When you declare the 'i' variable in your for loop, that's basically the starting place.

For example, given the array ['a', 'b', 'c', 'd'] and the loop:

  for (var i = 1; i < array.length; i++ ) {
     console.log(array[i]);
  }

that will print out 'b', 'c' and 'd' since the 'i' variable is 1 instead of 0, it won't print the first element. Make sense?