There are different ways to concatenate arrays in Javascript. The most common way is using the spread-syntax:
let a,b,c
a = [1,2,3,4]
b = [5,6,7...
For further actions, you may consider blocking this person and/or reporting abuse
Maybe I’m missing something, but could we possibly check if the value is an array first? If it is, using the spread operator seems like a neat way to go. And for single values, couldn’t we just stick to using .push(5) on the array? I’ve always found the push method pretty handy for adding individual values to arrays in JavaScript. What do you think?
You missed the main point: with flat() you do not need to check. Anything is just appended to the array, regardless if it's an array or a simple value.
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:
Your comment has definitely broadened my perspective. Thanks for sparking such a fascinating discussion.
It was more an accident to use flat(). Initially i tried to use this:
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:
I always forget about
Array.flat(). There's definitely someArray.isArray(val) ? [...a, ...val] : [...a, val]lines that I could simplify with it. :)Array.concat() does a similar job, it´s just a matter of taste:
It is amazing what is already implemented in the Javascript Arrays. See this overview:
Thank you Eckehard