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?

6
  • 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. Commented Aug 11, 2022 at 14:51
  • I'm now actually wondering if I could just flatten out the depth first and then nest some for loops? Commented Aug 11, 2022 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 Commented Aug 11, 2022 at 14:58
  • stackoverflow.com/questions/32634796/… 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. Commented Aug 11, 2022 at 15:04
  • 1
    I think this actually solves it perfectly: stackoverflow.com/questions/12303989/… Commented Aug 11, 2022 at 16:21

0

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.