Merge Two arrays in JavaScript

Last Updated On Monday 1st Nov 2021

JavaScript Concat Arrays

JavaScript Array Join.Merge Array Javascript.

Use Array.concat

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.

Syntax

	concat()
concat(value0)
concat(value0, value1)
concat(value0, value1, ... , valueN)
	

Parameters

  • value N Optional – Arrays and/or values to concatenate into a new array. If all valueN parameters are omitted, concat returns a shallow copy of the existing array on which it is called.
	const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];

const numbers = num1.concat(num2, num3);

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

Merge the arrays (without removing duplicates)

	let array1 = ["Adam", "Alice"];
let array2 = ["Danny", "Benny"];

console.log(array1.concat(array2));
// [ 'Adam', 'Alice', 'Danny', 'Benny' ]
	

JS Join Two Arrays

Use destructuring(())

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays.

Syntax

	const foo = ['one', 'two', 'three'];

const [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"
	
	let array1 = ["Adam", "Alice"];
let array2 = ["Danny", "Benny"];

console.log([...array1, ...array2]);
// [ 'Adam', 'Alice', 'Danny', 'Benny' ]
	

Merge Array with removing the Duplicates

	a = [1, 2, 3,"Adam"];
b = [3, 2, 1, "Adam"];

let ss = a.concat(b.filter(function(el) {
    return a.indexOf(el) === -1;
}));

console.log(ss);
// [ 1, 2, 3, 'Adam' ]