DEV Community

Discussion on: Better array concat...

Collapse
 
marco_cabrera_81e1796f41f profile image
marco cabrera • Edited

Ah, I see where you're coming from now. My bad for not catching on quicker. I've always leaned on the flat method for smashing down those layered arrays into one array. Seeing it used in the way you described threw me for a loop—but in a good, 'huh, never thought of it like that' kind of way. It's definitely not the standard route, but hey, if it works, it works. And actually, the more I think about it, the more clever it seems for dodging the whole 'is this a single item or an array?' headache.

Here's me, noodling around with some code after mulling over what you said:


let a,b
a = [1,2,3,4]
b = [5,6,7,8]
console.log([...a,...b]) // -> [ 1, 2, 3, 4, 5, 6, 7, 8 ]

a.push(...b)
console.log(a) // push using spread

a = [1,[2],3,4]
b = [5,6,7,[8]]
a.push(b)
console.log(a.flat(Infinity)) // how to flatten all the way down

a = [1,2,3,4]
b = [5,6,7,8]
let newArr = a.concat(b)
console.log(newArr)

a = [1, 2, 3];
b = [4, 5, 6];

let mergedArray = Array.from({ length: a.length + b.length }, (_, index) =>
    index < a.length ? a[index] : b[index - a.length]
);

console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]

Enter fullscreen mode Exit fullscreen mode

Your comment has definitely broadened my perspective. Thanks for sparking such a fascinating discussion.

Thread Thread
 
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