How to Merge Arrays in Javascript

Feb 6, 2024

2 mins read

Published in

How to Merge Arrays in JavaScript: A Comprehensive Guide

Understanding Arrays in JavaScript:

Before diving into merging arrays, let’s understand the basics of arrays in JavaScript. Arrays are ordered collections of values, indexed by a numerical index starting from 0. They can hold any type of data, including numbers, strings, objects, or even other arrays.

Traditional Approach:

One of the simplest ways to merge arrays in JavaScript is by using the concat() method. This method creates a new array by combining the elements of two or more arrays.

1
2
3
4
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArray = arr1.concat(arr2);
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]

ES6 Approach:

With the introduction of ES6, JavaScript provides more concise and powerful methods for array manipulation. One such method is the spread operator (...), which allows us to easily merge arrays.

1
2
3
4
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArray = [...arr1, ...arr2];
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]

This approach is more elegant and readable, especially when dealing with multiple arrays.

Handling Arrays with Duplicates:

If your arrays contain duplicate elements, you may want to remove duplicates before merging. One way to achieve this is by using the Set object, which stores unique values of any type.

1
2
3
4
const arr1 = [1, 2, 3];
const arr2 = [3, 4, 5];
const mergedArray = [...new Set([...arr1, ...arr2])];
console.log(mergedArray); // Output: [1, 2, 3, 4, 5]

This method ensures that the merged array contains only unique elements, eliminating any duplicates.

Sorting Merged Arrays:

Sometimes, you may need to sort the merged array in a specific order. JavaScript provides the sort() method, which sorts the elements of an array in place and returns the sorted array.

1
2
3
4
const arr1 = [3, 1, 4];
const arr2 = [2, 5, 6];
const mergedArray = [...arr1, ...arr2].sort((a, b) => a - b);
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]

By providing a custom comparison function to sort(), you can specify the sorting criteria.

Merging arrays in JavaScript is a fundamental operation with various methods available for accomplishing the task. Whether you prefer the traditional approach using concat() or the modern ES6 approach with the spread operator, JavaScript provides the flexibility to merge arrays efficiently based on your requirements. By understanding these methods and their capabilities, you can streamline your array manipulation tasks and write more concise and readable code.

Sharing is caring!