2

So, I am working with an array of arrays like this:

const arrOfArrs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

For my example problem, I can only access the individual elements by using a nested loop, I'd like to be able to (if possible) use a single loop, using destructuring to access the individual elements of each sub-array

Example (I know this works somewhat but not as intended): I need access to each element. And it needs to be flexible. In case I'm working with different sized arrays. (3 x 3 or 4 x 4 etc.) Writing the el1, el2, el3 wouldn't be flexible for other sized array of arrays

 arrOfArrs.forEach(([el1, el2, el3]) => console.log(el1));

Above would console log each first el of each sub array: example el1 would log: 1, 4 , 7. I'd like to get individual element 1, then 2, 3, 4 etc. And be able to loop through it all. Is this possible?

Thank you so much for your help!

  • 2
    Unless the indicies you need to target are hard-coded, destructuring won't work (at least not without some ugly convoluted code). Iterate over the array instead of trying to put each element into separate identifiers. – CertainPerformance May 21 '22 at 02:00

3 Answers3

3

You can use just Array#flat()

Code:

const arrOfArrs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

const destructuredArray = arrOfArrs.flat()

console.log(destructuredArray)
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
1

You can map over your parent arrays and spread each of them into a new container array, like so:

const arrOfArrs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

const destructuredArray = [] 

arrOfArrs.map(array => destructuredArray.push(...array))

console.log(destructuredArray)

Is this the kind of thing you're aiming for?

Marco
  • 511
  • 6
  • 16
  • It is not performant to iterate over the `arrayOfArrs` with `Array#map()`, then calling `Spread syntax` for all of the nested arrays and pushing the result to `destructuredArray` variable when you can just use `Array#flat()` – Yosvel Quintero May 21 '22 at 07:26
0

To truly access each item in a single loop, you first want to flatten the array as done here: https://stackoverflow.com/a/10865042/6127393
In the snippet below I am directly iterating the flattened array result without storing it in a new variable (basically a 'one-liner').

const arrOfArrs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
[].concat.apply([], arrOfArrs).forEach(one => {
  console.log(one)
});
Arleigh Hix
  • 9,990
  • 1
  • 14
  • 31