concatenate 2 arrays in javascript code example

Example 1: combine two arrays javascript

let arr1 = [0, 1, 2];
let arr2 = [3, 5, 7];
let primes = arr1.concat(arr2);

// > [0, 1, 2, 3, 5, 7]

Example 2: merge array in js

//for ES5
var array1 = ["Rahul", "Sachin"];
var array2 = ["Sehwag", "Kohli"];

var output = array1.concat(array2);
console.log(output);

//for ES6, we use spread operators to concat arrays

var array1 = ["Dravid", "Tendulkar"];
var array2 = ["Virendra", "Virat"];

var output = [...array1, ...array2];
console.log(output);

Example 3: concat array javascript

const letters = ['a', 'b', 'c'];
const numbers = [1, 2, 3];

const newArray = letters.concat(numbers);
// newArrat is ['a', 'b', 'c', 1, 2, 3]

Example 4: combine 2 arrays javascript

//ES6 using the spread operator
const itemsA = [ 'Lightsaber', 'Mockingjay pin', 'Box of chocolates' ];
const itemsB = [ 'Ghost trap', 'The One Ring', 'DeLorean' ]
const allItems = [ ...itemsA, ...itemsB ];

Example 5: array merge in javascript

function mergeArrays(arr1, arr2) {
  return Array.from(new Set(arr1.concat(arr2).sort((a,b) => (a-b))));
}