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

174
Views
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 answers
Answer question

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 Report

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 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!