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?
CodePudding user response:
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))
CodePudding user response:
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);