0

I have an array which contains arrays of objects, that resembles this:

[{a:1}, {a:2}, {a:3}], [{b:1}, {b:2}], [{c:1}, {c:2}]

I don't know how many arrays there will be or how many objects inside them.

What I want to do is extract each object from the arrays and push them into a new array of objects where there is every possible combination of object, like this:

[
  { a:1, b:1, c:1 },
  { a:1, b:1, c:2 },
  { a:1, b:2, c:1 },
  { a:1, b:2, c:2 },
  { a:2, b:1, c:1 },
  { a:2, b:1, c:2 },
  { a:2, b:2, c:1 },
  { a:2, b:2, c:2 },
  { a:3, b:1, c:1 },
  { a:3, b:1, c:2 },
  { a:3, b:2, c:1 },
  { a:3, b:2, c:2 }
]

I've started to consider that the method might be to get the value from the a:1 object, and then loop over the others, but I'm wondering if there's an efficient pattern to solve this restructuring?

daggett
  • 239
  • 2
  • 4
  • 15
  • If I understand correctly, you're trying to do what a nested for loop would normally do, but you don''t know the depth ahead of time? If so, consider using a counter variable and do division and mod operations on it. – Barry Carter Aug 11 '22 at 14:51
  • I'm now actually wondering if I could just flatten out the depth first and then nest some for loops? – daggett Aug 11 '22 at 14:57
  • 1
    The problem is you don't know how many for loops in advance, even with flattening (unless I'm missing something). I'm willing to bet someone's written a function to do this, so, unless you're doing this to learn, google might help – Barry Carter Aug 11 '22 at 14:58
  • https://stackoverflow.com/questions/32634796/loop-through-values-in-arrays-in-an-array-output-all-combinations provides a recursive solution, though I personally am opposed to recursive functions in general, since they can fail if you ... do exactly what this site is named. – Barry Carter Aug 11 '22 at 15:04
  • I think I should be able to flatten to consistently have [{a:1}, {a:2}, {a:3}], [{b:1}, {b:2}], [{c:1}, {c:2}] as the template array. So I suppose from there it's just up to for loops and for...in for the objects. Thanks for the advice and links. – daggett Aug 11 '22 at 15:08
  • 1
    I think this actually solves it perfectly: https://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript – daggett Aug 11 '22 at 16:21

0 Answers0