Catalin Vasile

I'm a design-focused engineer.

JavaScript Bits: How to merge two Arrays?

In this short guide, you will learn how to merge two Array types in JavaScript. Keep in mind that the methods available are highly dependent on the JavaScript version you’re using.

But don’t worry, we’re going to cover them all. Let’s go!

ES5

In ES5 you can merge two Arrays using the .concat() method.

var fruits = ['apples', 'peaches'];
var vegetables = ['potatoes', 'tomatoes'];

var all = fruits.concat(vegetables); // apples, peaches, potatoes, tomatoes

The .concat() method simply creates a new Array using the elements of the Array it’s being used on, and the elements of the argument received. There are two important things to note about how .concat() works:

  • It does not recurse into nested array arguments. It simply creates a shallow copy.
  • It does copy object references into the new Array.

Removing duplicates from an Array in ES5

If you’d like to also remove duplicates, you can do so using the .filter() method. Another method is using the Lodash .union() method.

var fruits = ['apples', 'apples'];
var vegetables = ['potatoes', 'potatoes'];

var all = fruits.concat(vegetables); // apples, peaches, potatoes, tomatoes

// remove all duplicates: apples, potatoes
var unique = all.filter(function (item, index) {
    return all.indexOf(item) === index;
});

ES6

In ES6 you can merge two Arrays using destructuring.

const fruits = ['apples', 'peaches'];
const vegetables = ['potatoes', 'tomatoes'];

const all = [...fruits, ...vegetables]; // apples, peaches, potatoes, tomatoes

In ES6 you can also “merge” two Arrays using the .push() method. I wouldn’t necessarily call it merging two Arrays, but it’s an alternative.

const fruits = ['apples', 'peaches'];
const vegetables = ['potatoes', 'tomatoes'];

fruits.push(vegetables);

console.log(fruits); // apples, peaches, potatoes, tomatoes

Removing duplicates from an Array in ES6

In ES6 we can remove duplicates from an Array using a Set.

const fruits = ['apples', 'apples'];
const vegetables = ['potatoes', 'potatoes'];

const all = [...fruits, ...vegetables];

// remove all duplicates
const unique = [...new Set(all)]; // apples, potatoes

Sets are collections which values occur only ones. Basically a Set is an iterable with unique values. Pretty neat, right?

You can learn more about Sets in ES6 here.

Conclusion

That’s it! I hope this short guide has helped you better understand how to merge two Array types in both ES5 and ES6. Let me know your thoughts in the comments below!

Subscribe

Be the first to know when I publish a new article on the blog.

No spam. You can unsubscribe at any time.


Comments