Home > Blockchain >  Destructuring array of arrays to get access to individual elements
Destructuring array of arrays to get access to individual elements

Time:05-21

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!

CodePudding user response:

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?

CodePudding user response:

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)
});

  • Related