Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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])
}

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!