1

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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

8 Comments

Is this possible in native JS? I'm struggling with creating nested for loops dynamically
@user2402616 hi im using native js array methods map, reduce, flatMap, join, concat
@user2402616 not sure what u meant by native js here. can u elaborate
@user2402616 flatmap is basically calling map().flat() in order. you will find custom implementations for these higher order functions using loops on stackoverflow
should be possible. might need some recursion i guess stackoverflow.com/a/29585704/13583510
|
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.