Combining Arrays

In this 2 Minute Tool Tip, we'll continue exploring the Javascript Spread Operator .... If you'd like to read how the Spread Operator simplifies passing an array to a function, check out the previous 2 Minute Tool Tip.

ES6 has really simplified working with arrays in general. Let's look at combining arrays.

The Old Way

concat(..) is probably the most common approach to joining two arrays.

var arrA = [1,2,3,4]; 
var arrB = ['js', 'can', 'be', 'laborious'];

// let's join the two arrays into (a new) array
var arrC = arrA.concat(arrB);

console.log(arrA); // [1,2,3,4]
console.log(arrB); // ['js', 'can', 'be', 'laborious']
console.log(arrC); // [1,2,3,4,'js', 'can', 'be', 'laborious']

Great. That was relatively easy. Sort of...

Think about how many times you've coded something along these lines. Why are your creating the combined array c? Do you still need arrays a and b? Let's think about that in another, longer post

The ES6 Way

To replicate the concat(..) prototype, we can just put arrA into arrB. Here:

let arrA = [2,3];
let arrB = ['es6', 'looks', 'simpler'];

// let's join the two arrays into a new array
let arrC = arrA.push(...arrB);    // puts arrB on the end of arrA
let arrD = arrB.push(...arrA);    // puts arrA on the end of arrB
let arrE = arrA.unshift(...arrB); // puts arrB at the beginning of arrA

console.log(arrC); // [2,3,'es6', 'looks', 'simpler']
console.log(arrD); // ['es6', 'looks', 'simpler',2,3] 
console.log(arrE); // same as arrD, just a different way to call it  

Not much efficiency there.

Let's go back and think about why you'd want to join arrays. If you really don't need to create a third array, you could:

let arr1 = [2,3];
let arr2 = [1, ...arr1, 4];

console.log(arr2); // [1,2,3,4]  

Now, that's pretty neat.