DEV Community

Discussion on: Better array concat...

 
efpage profile image
Eckehard • Edited
  • If you mark your codeblocks with ' ' ' JS they get coloured
  • Do you know flems.io? It is a pretty neat way to show your running code and let people play around with it.

It was more an accident to use flat(). Initially i tried to use this:

const concat = (...x) => x
a = [1,2,3,4]
b = 5
c = concat(a,b) 
console.log(c) // -> [ [ 1, 2, 3, 4 ], 5 ]
Enter fullscreen mode Exit fullscreen mode

But then you come up with a nested array.

I would prefer to use flat without parameter. flat() ist like flat(1), so it flattens only one level. This let´s you preserve the structure of the initial arrays:

a = [1,[2,3],4]
b = [6,[7,8],9]

c = [a,5,b].flat()
console.log(c) // -> [ 1, [ 2, 3 ], 4, 5, 6, [ 7, 8 ], 9 ]
Enter fullscreen mode Exit fullscreen mode