Has javascript any inbuilt method Is it possible to merge/combine two arrays in the same order as they are? This a basically simple task and could be solved by iterating over the min-length of both and adding each value to the new array:
var a = [1, 2, 3]
var b = [4, 5, 6]
var c = []
for (var i = 0; i < 3; i++) {
c.push(a[i])
c.push(b[i])
}
// => [1, 4, 2, 5, 3, 6]
However, I just asked me if that could be done with any inbuilt method. First I thought about concat
and sort
, but that feels like overkill (in contrast to a loop and performance)...
a.concat(b).sort(doItRight)
To be a bit more specific, those arrays could contain strings
and numbers
...
var a = [0, '1', 'c']
var b = ['d', 4, 'f']
var c = [0, 'd', '1', 4, 'c', 'f']
Any thoughts or ideas?
Update
Just forgot to note that the input arrays could be more more than two. I really like how reduce works in this case, and since the answers in the duplicate question use ugly nested loops, I thought reduce could help?
Update 2
There's String.raw
which could be abused to zip strings together:
String.raw({ raw: '123 ' }, 4, 5, 6)
// => '142536'