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

216
Views
Is there an efficient way to show images based on a route and file name using javascript?

Right now I have something like

const route = '/Images/Banner/'
const slides = [
  {
      name: "banner-01",
      url: `${route}banner-01.png`
  },
  {
      name: "banner-02",
      url: `${route}banner-02.png`
 
  },
  {
      name: "banner-03",
      url: `${route}banner-03.png`
  },
]
]

In this, I'm manually adding each image and it's properties because there are only 3 images, but i want to dynamically add them based on the quantity of images with the same name (they'll always are going to be named banner-NN).

Is there an efficient way to iterate through images with the same pattern of name ('banner-') and place them in an array of objects?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Iterating over the indicies of a collection and then inserting the indicies into the strings is easy enough...

const route = '/Images/Banner/'
const slides = Array.from(
  { length: 3 }, // 1 to 3
  (_, i) => {
    const numStr = String(i + 1).padStart(2, '0');
    return {
      name: `banner-${numStr}`,
      url: `${route}banner-${numStr}`,
    };
  }
);
console.log(slides);

about 4 years ago · Juan Pablo Isaza Report

0

@CertainPerformance's answer is fine but it relies on Array.from which not all browsers support. Just putting my way of doing this out there

const route = "/Images/Banner/";
const slides = [];
const totalItems = 100;

for (let index = 0; index < totalItems; index++) {
  const banner = `banner-${index.toString().length > 1 ? index : `0${index}`}`;

  slides.push({
    name: banner,
    url: `${route}${banner}.png`,
  });
}

console.log(slides);

about 4 years ago · Juan Pablo Isaza 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!