How to merge arrays in JavaScript

Sep 10, 2023#javascript#how-to

Merging arrays in JavaScript is a fundamental operation in web development. This process involves combining the elements of two or more arrays into a single, unified array.

Whether you prefer concise methods like the spread operator (...) or need more control using functions like concat(), this post will provide you with the knowledge you need to merge arrays effectively and streamline your JavaScript code.

  1. Using spread operator (...)

This is a feature of ES6 that allows you to expand the elements of an iterable (such as an array) into individual arguments. It also preserves the order of the arrays and works with any number of arrays.

The spread operator itself does not remove duplicate elements from an array. It simply spreads the elements of one array into another, retaining all the elements, including duplicates.

const array1 = [1, 2, 3];
const array2 = [3, 4, 5];
const array3 = [...array1, ...array2];
console.log(array3); // [ 1, 2, 3, 3, 4, 5 ]

If you want to remove duplicate elements from an array, you can use other JavaScript methods like Set or write a custom function.

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4, 5]

Keep in mind that the spread operator performs shallow copying, which means it creates new references for the top-level elements in arrays or objects. Nested objects and arrays will still be shared references, so modifying them in the new array or object will affect the original as well. If you need to perform a deep copy, you may need to use other techniques or libraries like Lodash.

  1. Using the concat() method

The concat() method in JavaScript is used to merge two or more arrays. It does not modify the original arrays but instead returns a new array containing the concatenated elements. It also preserves the order of the original arrays and does not remove duplicates.

const array1 = [1, 2, 3];
const array2 = [3, 4, 5];
const mergedArray = array1.concat(array2);

console.log(mergedArray); // [ 1, 2, 3, 3, 4, 5 ]
console.log(array1); // [ 1, 2, 3 ]
  1. Using the push() method

The push() method in JavaScript is used to add one or more elements to the end of an array. It does not merge arrays; instead, it adds new elements to an existing array. It maintains the order of elements, and does not remove duplicates.

You can use the push() method in combination with the spread operator to add elements from one array to another.

const array1 = [1, 2, 3];
const arrar2 = [3, 4, 5];
array1.push(...arrar2);
console.log(array1); // [1, 2, 3, 3, 4, 5]