Four ways to merge arrays in JavaScript

Four ways to merge arrays in JavaScript

Learn different ways to merge array in JavaScript

Image for postImage by Makarios Tang

1. Using for loop

We can loop through the array source array which need to be pushed , then add elements one by one

function push(fromArray, toArray) { for(let i = 0, len = fromArray.length; i < len; i++) { toArray.push(fromArray[i]); } return toArray;}var array1 = [1,2,3,4,5];var array2= [6,7,8,9,10];var array3 = ;push(array1, array3);push(array2, array3);

2. Using spread operator

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected

var array1 = [1,2,3,4,5];var array2 = [6,7,8,9,10];var array3 = […array1, …array2];array3; // [1,2,3,4,5,6,7,8,9,10];

We can use spread operator with push

var array1 = [1,2,3,4,5];var array2 = [6,7,8,9,10];var array3 = array3.push(…array1, …array2);array3; // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

We can also use spread operator with Array.of

var array1 = [1,2,3,4,5]var array2 = [6,7,8,9,10];var array3 = Array.of(…array2, …array1);

We can use spread operator to convert string to array

var string =”two”;var arrayOfChar = […string];arrayOfChar; //[“t”, “w”, “o”]

3. Using concat method

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

var array1 = [1,2,3,4,5]var array2 = [6,7,8,9,10];var array3 = array1.concat(array2);// orvar array3 = .concat(array1, array2);

We can pass other than array as arguments.

var a = “string”;var b = 1;var c = {};var combined = .concat(a, b, c)combined; // [“string”, 1, {?}]

4. Using Reduce method

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

var array1 = [1,2,3,4,5];var array2 = [6,7,8,9,10];var array3 = array2.reduce((newArray, item) => { newArray.push(item); return newArray; ), array1);

No Responses

Write a response