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,8]
c = [...a,...b] // -> [ 1, 2, 3, 4, 5, 6, 7, 8 ]
more ways shown here.
But what, if you need to deal with flexible types?
a = [1,2,3,4]
b = 5
c = [...a,...b] // -> b is not iterable
I came across this problem in a routine, that got passed some variables, that could be either arrays or single values. Doing some type checks would be an option, but how to deal with the different possible cases? Finally I came across a dead simple solution, that does not require any programming at all:
a = [1,2,3,4]
b = 5
c = [a,b,6].flat() // [ 1, 2, 3, 4, 5, 6 ]
The flat-operator flatens only one level, so this works also with nested arrays. If you want deepter flattening, you can specify the depth using flat(n).
Talking of functions, the trick can also be used with function parameters:
const concat = (...x) => x.flat()
a = [1,2,3,4]
b = 5
c = concat(a, b, 6) // -> [ 1, 2, 3, 4, 5, 6 ]
More Advantages of using flat()
By default, Javascript creates "shallow copies" of arrays (copy by reference). This might have unwanted effects:
a = [1,2,3,4]
d = a
d[2]=99
console.log(a) // -> [ 1, 2, 99, 4 ]
console.log(d) // -> [ 1, 2, 99, 4 ]
Here we changed a without touching it. "a" and "d" share the same data. If we want to create a real copy with separate data, flat(0) is one option:
let a,b,d
a = [1,2,[3,4]]
d = [...a]
d = a.flat(0)
d[1]=99
console.log(a) // -> [ 1, 2, [ 3, 4 ] ]
console.log(d) // -> [ 1, 99, [ 3, 4 ] ]
Thank you Eckehard