top of page
Writer's pictureThe Tech Platform

3 Methods to Merge an Array in JavaScript



An array is a data structure representing an ordered collection of indexed items.


A common operation performed on multiple arrays is merge — when 2 or more arrays are merged to form a bigger array containing all the items of the merged arrays.


For example, having two arrays [1, 2] and [5, 6], then merging these arrays results in [1, 2, 5, 6].


1. Spread Operator

Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 values are expected. It allows us the privilege to obtain a list of parameters from an array


Example:

const word1 = ['Welcome', 'to'];
const word2 = ['The', 'Tech', 'Platform'];
console.log("1st Method to Merge Array is Spread Operator", "\n");
console.log(...word1, ...word2); 

Output:






2. Push Operator

Javascript array push() method appends the given element(s) in the last of the array and returns the length of the new array.


Example:

const animals = ['pigs', 'goats', 'sheep'];
console.log("Array =" , animals , '\n');

animals.push('chickens', 'cats', 'dogs');
console.log("Array after using Push Operator = ", '\n', animals);

Output:




3. Concat Operator

The JavaScript concat() method merges the contents of two or more strings. You can also use the + concatenation operator to merge multiple strings. ... Concatenation is a technique used in programming to merge two or more strings into one value.


Example:

const cars1 = ['Ferrari', 'Suzuki', 'Jeep'];
const cars2 = ['Hyundai' , 'kia']
console.log("List of Cars =" ,'\n',"Array 1" , cars1,'\n',"Array 2" ,cars2, '\n');
const newcars = cars1.concat(cars2);
console.log("List of cars after using Concat Operator = ", '\n', newcars);

Output:











The Tech Platform

0 comments

Recent Posts

See All

Comments


bottom of page