Merging of Arrays in JavaScript

Use-Cases of this Tutorial

  • Know how to merge multiple arrays in Javascript.

Concepts and Methods Used

  • concat() method to merge multiple arrays
  • Set object and Spread operator to eliminate duplicates from merged array (if required)

Using concat() to Merge Arrays

The concat() method can be used to merge two or more arrays.

concat() accepts any number of parameters. Each parameter represents an array that is to be merged to the input array. The input array is not changed, and the new merged array is returned.

var array_first = [1, 2, 3];
var array_second = [3, 4, 5];
var array_third = ['a', 'b', 'c'];

// merges the arrays, starting from the calling array
var merged = array_first.concat(array_third, array_second);

// [1, 2, 3, "a", "b", "c", 3, 4, 5]
console.log(merged);

Merging with Duplicates Removal

The concat() method does not eliminate duplicate values from the merged array, but sometimes it may be required.

See also  CSS Only Pinterest-like Responsive Board Layout - Boardz.css

The simplest way to eliminate duplicates from the merged array is to create a Set object — creating a Set from the merged array will automatically eliminate duplicates.

The Set object can again be converted to an array with a for .. of loop, or in a shorter syntax using the Spread operator.

var array_first = [1, 2, 3];
var array_second = [3, 4, 5];
var array_third = [4, 5, 6, 7];

// merge
var merged = array_first.concat(array_third, array_second);

// create Set from merged array
var merged_set = new Set(merged);

// Set to array
merged = [ ...merged_set ];

// [1, 2, 3, 4, 5, 6, 7]
console.log(merged);

Leave a Reply

Your email address will not be published. Required fields are marked *