Join Nested Array

Join Nested Array
0

#1

Hello, FreeCodeCampers.

I want to ask how we can join nested array.

Let’s say I have:

section = [
  ['section-0-0', 'section-0-1'],
  ['section-1-0', 'section-1-1']
];

I want to apply it to CSS Grid as grid-template:'s content. So the inner array will be separated by space, then outer array will be separated by new line. Can I do that?

The semi-result I want is:

semiResult = ['section-0-0 section-0-1', 'section-1-0 section-1-1'];

The result I want is:

finalResult = "'section-0-0 section-0-1'\n'section-1-0 section-1-1'";

If it’s in React, I’ve read the rows of gridTemplate can be separated by space. I don’t know if it can be directly manipulated to finalResult or we have to go to semiResult first.

Thanks.

Edit:
I’m afraid it is already covered everywhere but I don’t know how to phrase it because when I search for “how to join nested array” I don’t find any problem like this. Maybe other keywords?


#2

When you say join a nested array, are you wanting to create a single array of the section array’s sub array’s (like flattening out the array? You need to show what the final result should look like, because joined to me could either be a single array of with each sub array element as an element in the single array, or you could want a string with all the sub array elements joined. Just let us know.


#3

Assuming you want this

'section-0-0 section-0-1\nsection-1-0 section-1-1'

then you could do this

section.map(arr => arr.join(' ')).join('\n');

#4

@RandellDawson, I have edited it.

@colinthornton, wow thanks. So it should be mapped first. But how can I preserve the inner quote? Like this:

"'section-0-0 section-0-1'\n'section-1-0 section-1-1'"

I think I can modify the section variable in the first place like this:

section = [
  [`'section-0-0'`, `'section-0-1'`],
  [`'section-1-0'`, `'section-1-1'`]
];

#5

Then we’d just need to wrap the stringified inner arrays with single quotes, which could be done like so:

section.map(arr => `'${arr.join(' ')}'`).join('\n');

#6

Here are links to all the relevant docs: