0

If I had a collection like this:

var array = {
    "fruit": ["apple","banana"],
    "amount": ["1", "2", "3"],
    "orign": ["africa", "asia", "europe"],
    ...
    "n": ["0", "...", "n"]
}

How would I get all combinations in a JSON format like this:

[
 {
   "fruit": "apple",
   "amount": "1",
   "orign": "africa"
 }
 {
   "fruit": "apple",
   "amount": "1",
   "orign": "asia"
 }
 ...
]

Is it possible to loop through all elements in a iterative manner? Or would I end up writing n loops?

  • You could do this: `const arrays = Object.values({ "fruit": ["apple","banana"], "amount": ["1", "2", "3"], "orign": ["africa", "asia", "europe"] }); 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); console.log(cartesian(...arrays));` – David Kiff Nov 06 '18 at 21:33

1 Answers1

0

I believe you are looking for the "cartesian product" (assuming the arrays are sets). Your question (in a slightly different way) has been previously discussed in here. You can see different solutions in there, including a recursive solution, and many functional programming like.

I hope it helps,

Cheers!