Here’s another computer science classic: how do you merge two arrays?

My preferred way in 2018 is to use the spread operator, though previously concat() was probably the most common approach. You can also use a for loop in interesting ways to achieve the same result.

const a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
const b = [ "foo", "bar", "baz", "bam", "bun", "fun" ];

// Spread operator
const c = [...a, ...b];

// Concat
const c = a.concat(b);

// Loop insertion
for (let i=0; i < b.length; i++) {
  a.push(b[i]);
}

// Loop insertion going backwards
for (let i=a.length-1; i >= 0; i--) {
  b.unshift(a[i]);
}

What if the two arrays are sorted? Check out How to Merge Two Sorted Arrays.



Want to improve your JavaScript? I have a list of recommended JavaScript books.



Want to improve your JavaScript? I have a list of recommended JavaScript books.