Easy ways to Array merge javascript 2021
August 01, 2021Today we are going to learn about array merge javascript with example.
We are going to see multiple methods to merge arrays
Array merge Javascript using Spread Operator
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const merged = [...array1, ...array2];
const all = […array1, …array2] creates a new array having array1 and array2 arrays merged.
The order of merged arrays is inserted in the same order as the arrays that appear inside the variable merged.
For example, let’s put the list of array2 before the list of array1 in the merged array:
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const all = [...array2, ...array1];
all; // [4,5,6,1,2,3]
The spread operator approach lets you merge 2 and even more arrays at once:
const mergeResult = [...array1, ...array2, ...array3, ...arrayN];
Array merge Javascript using Concat Method
If you prefer a functional way to merge arrays, then you can use the array1.concat(array2) method:
// merge array1 and array2
const merged = array1.concat(array2);
or using another form:
// merge array1 and array2
const merged = [].concat(array1, array2);
array.concat() the method doesn’t mutate the array but returns a new array having the merge result.
Let’s use array.concat() to merge the arary1 and array2:
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const merged1 = array1.concat(array2);
const merged2 = [].concat(array1, array2);
merged1; // [1,2,3,4,5,6]
merged2; // [1,2,3,4,5,6]
array1.concat(array2) as well as [].concat(array1, array2) return a new array where array1 and array2 arrays are merged.
The concat method accepts multiple arrays as arguments, thus you can merge 2 or more arrays at once:
const mergeResult = [].concat(array1, array2, array3, arrayN);
Array merge Javascript using Push Method
array.push(item) method pushes an item at the end of the array, mutating the array.
const array1 = [1, 2, 3];
array1.push(4);
array1; // [1,2,3,4]
array.push(item1, item2, …, itemN) accepts multiple items to push, we can push also push N number of arrays using the spread operator.
// merge array2 into array1
array1.push(...array2);
// merge array2 into array1 array1.push(…array2);
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
array1.push(...array2);
array1; // [1,2,3,4,5,6]
array1.push(…array2) pushes all the items of array2 array at the end of array1 array — performing a mutable merge. array1 is mutated.
Array merge javascript without duplicates
We learnt 3 methods to merge arrays. Now we are going to merge the array without duplicates
let array1 = ["a", "b", "c"];
let array2 = ["c", "c", "d", "e"];
//Concat method
let merged = array1.concat(array2);
let unique = [...new Set(merged)];
//a,b,c,d,e
//Spread operator method
let merged = [...array1, ...array2];
let unique = [...new Set(merged)];
//a,b,c,d,e
In the next post, we can see how to merge the javascript objects.
Related Posts,