How to iterate through an array which contain less than the iterator value

Viewed 81

the title is bit confusing so sorry about that, so what i have is a too arrays one of the array contain more then the second array

   x = [1,2,3,4,5];
    y =  [{
          x: "test1",
          y: "test2",
          z: "test3",
          w: `test4`
        }] 

so what I want to do is for example

 for (let i = 0; i < x.length; i++) {
     console.log(y[i])
}

which would only log out the first one one time but what i want is to log y as many as x length hope that was clear enough

1 Answers

You can use the remainder operator to get the corresponding item from the shorter array:

const x = [1, 2, 3, 4, 5];
const y = [{"x":"test1","y":"test2","z":"test3","w":"test4"},{"x":"test21","y":"test22","z":"test23","w":"test24"}]

for (let i = 0; i < x.length; i++) {
  const idx = i % y.length;
  console.log(y[idx])
}

Or you can use the last index of the y array, if the current i value is over the length of the last item index in the y array:

const x = [1, 2, 3, 4, 5];
const y = [{"x":"test1","y":"test2","z":"test3","w":"test4"},{"x":"test21","y":"test22","z":"test23","w":"test24"}]

for (let i = 0; i < x.length; i++) {
  const idx = Math.min(i, y.length - 1)
  console.log(y[idx])
}

Related