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.


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?

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.

Assuming you want this

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

then you could do this => arr.join(' ')).join('\n');

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

Then we’d just need to wrap the stringified inner arrays with single quotes, which could be done like so: => `'${arr.join(' ')}'`).join('\n');

Here are links to all the relevant docs: