It all starts with me seeing this question:
let names = ["iPhone X"."iPhone XS"]
let colors = ["Black"."White"]
let storages = ["64g"."256g"]
Copy the code
You have arrays that list all their combinations, and you end up with something like this:
[["iPhone X"."Black"."64g"],
["iPhone X"."Black"."256g"],
["iPhone X"."White"."64g"],
["iPhone X"."White"."256g"],
["iPhone XS"."Black"."64g"],
["iPhone XS"."Black"."256g"],
["iPhone XS"."White"."64g"],
["iPhone XS"."White"."256g"]]Copy the code
The difficulty of this problem is that the number of arrays above can be added or deleted, so it cannot be solved by simply iterating through the above three arrays. You can pause here for a moment and think of your own solutions.
The solution
It took me half an hour to write the code, but I found it was not as elegant as the big guy wrote, so here is the big guy’s solution for your reference.
let names = ["iPhone X"."iPhone XS"]
let colors = ["Black"."White"]
let storages = ["64g"."256g"]
let combine = function (. chunks) {
let res = []
let helper = function (chunkIndex, prev) {
let chunk = chunks[chunkIndex]
let isLast = chunkIndex === chunks.length - 1
for (let val of chunk) {
let cur = prev.concat(val)
if (isLast) {
// Put the result of the concatenation into the return value if you have reached the last item in the array
res.push(cur)
} else {
helper(chunkIndex + 1, cur)
}
}
}
// Start processing from the property array subscript 0
// Prev is an empty array
helper(0[]),return res
}
console.log(Combine (names, colors, Storages))//juejin.im/post/5ee6d9026fb9a047e60815f1The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.Copy the code
If you are interested, you can also take a look at the article “Is it difficult to complete the permutation algorithm of skU of front-end e-commerce? Learn this routine and thoroughly master permutation and combination”, which also has the author’s solution ideas and extended knowledge sharing.
extension
The solution to cartesian product problems can be found in stackOverflow (****). The solution can be found in stackOverflow (****).
const f = (a, b) = >[].concat(... a.map(d= > b.map(e= > [].concat(d, e))));
const cartesian = (a, b, ... c) = >(b ? cartesian(f(a, b), ... c) : a);let output = cartesian([1.2], [10.20], [100.200.300]);
Copy the code
Output the output
[[1.10.100 ],
[ 1.10.200 ],
[ 1.10.300 ],
[ 1.20.100 ],
[ 1.20.200 ],
[ 1.20.300 ],
[ 2.10.100 ],
[ 2.10.200 ],
[ 2.10.300 ],
[ 2.20.100 ],
[ 2.20.200 ],
[ 2.20.300]]Copy the code
You read that right. Two lines of code. Take my knee, big man. Cartesian Product of Multiple Arrays in JavaScript