Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
How to create a nested while loop based on N number of arrays?

I'm trying to create a combination of all possible variants of the arrays given below, which are pretty self-explanatory.

let arr1 = ['Small', 'Medium', 'Large', 'Extra-Large']
let arr2 = ['Black','Red','White']
let arr3 = ['Normal','Limited-Edition']

let combos = []

arr1.forEach((i) => {
  arr2.forEach((j) => {
    arr3.forEach((k) => {
      combos.push(i + '-' + j + '-' + k)
    })
  }) 
})

console.log(combos)

This gives the output I want, however I want to create a function that takes an arbitrary array of arrays, [arr1, arr2, arr3.....arrN] and creates a nested loop of each of them, and returns a combined value of strings.

How do I go around creating such a function?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can use something like this using reduce. I referenced this post

let arr1 = ['Small', 'Medium', 'Large', 'Extra-Large'] 
let arr2 = ['Black','Red','White']
let arr3 = ['Normal','Limited-Edition']
let arr4 = ['x','y','z']

let arr = [arr1,arr2,arr3,arr4]

 let combined = arr.reduce((a,c)=>{
    return a.flatMap(x=>c.map(y=>x.concat(y)))
},[[]]).map((z) => z.join("-"))
 
 console.log(combined)
  console.log(combined.length) //4*3*2*3 = 72

UPDATE - This one is taken directly from the top answer with a very small modification

let arr1 = ['Small', 'Medium', 'Large', 'Extra-Large'] 
let arr2 = ['Black','Red','White']
let arr3 = ['Normal','Limited-Edition']
let arr4 = ['x','y','z']

let arr = [arr1,arr2,arr3,arr4]

const cartesian =
  (a) => a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat()))).map(x=>x.join("-"));

console.log(cartesian(arr))

about 4 years ago · Juan Pablo Isaza Denunciar

0

    const arr1 = ['Small', 'Medium', 'Large', 'Extra-Large'] 
    const arr2 = ['Black','Red','White']
    const arr3 = ['Normal','Limited-Edition']
    const arr4 = ['x','y','z']
  
    const arr = [arr1,arr2,arr3,arr4]
    const merged = [].concat.apply([], arr);

    console.log(merged);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda