Join Nested Array

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?

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

@camperextraordinaire, 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'`]
];

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

Here are links to all the relevant docs: