0

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'

yckart
  • 32,460
  • 9
  • 122
  • 129
  • 1
    This function is usually called `zip`, it's not built-in in JS, but easy to implement - see [here](http://stackoverflow.com/q/4856717/989121). And you need to flatten the zip result with `[].concat.apply([], zip(arrays))` – georg Feb 27 '16 at 22:10
  • @georg Eh, nope... I just need one array as the result... that's not `zip` ;) – yckart Feb 27 '16 at 22:12
  • Yeah, just realized that, reopened and edited the comment. ^^^^ – georg Feb 27 '16 at 22:12
  • Yup, saw it... that's in anyway a lot more overkill than *just* `concat`/`sort` :P – yckart Feb 27 '16 at 22:14
  • If you're looking for performance, nothing beats a simple for loop. – georg Feb 27 '16 at 22:14
  • 2
    You can't use .sort() here, because the order you want doesn't relate to the values themselves, it relates to where the values came from. Just put the loop you've shown in a function and move on - after adding some length checking in case the input arrays have different lengths. – nnnnnn Feb 27 '16 at 22:16

1 Answers1

0

There's no built-in function, but there are more functional ways to do it. Usually, if I've got a working solution of the form "create an array, then loop over something and append to the array", I reach for reduce instead. You can define a zip function using reduce like so:

const zip = (a,b) => a.reduce( (c,x,i) => c.concat(x, b[i]), [] );

Here's a demonstration:

const zip = (a, b) => a.reduce((c, x, i) => c.concat(x, b[i]), []);
const a = [1, 2, 3];
const b = [4, 5, 6];
console.log( zip([1, 2, 3], [4, 5, 6]) );
//=> [ 1, 4, 2, 5, 3, 6 ]
console.log( zip([0, '1', 'c'], ['d', 4, 'f']) );
//=> [ 0, 'd', '1', 4, 'c', 'f' ]
Mark Reed
  • 91,912
  • 16
  • 138
  • 175