0

Suppose I'm iterating over data and building up a multi-dimensional array. Inside the loop I want to do:

arr[x][y].push(z);

But if it's the first time a particular value has been seen for x or y then the array doesn't exist yet.

Is there an idiom in JS for doing this?

EDIT: Edited to make it clear this is about arrays, not objects.

8
  • No, sorry. PHP will do it, JS has nothing automatic. Commented Nov 9, 2023 at 23:11
  • You can use conditional chaining when reading a nested value if the intermediates might not exist, but there's nothing similar for creating. Commented Nov 9, 2023 at 23:12
  • 1
    Note that unless cake and ingredient are numbers, you likely want to be using an object for arr than an array... Commented Nov 9, 2023 at 23:13
  • @Barmar ((arr ??= [])[cake] ??= [])[ingredient] = quantity; (or if they're not numeric indices, ((arr ??= {})[cake] ??= {})[ingredient] = quantity;) Commented Nov 10, 2023 at 0:12
  • @Bergi Ugh! Remember when they complained Perl was a write-only language? Commented Nov 10, 2023 at 0:14

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.