JavaScript: Merge two arrays
Ways to merge two or more arrays in Javascript and which one is more effective
by Varit Patel
JavaScript
const fruits1 = ["π", "π", "π"];
const fruits2 = ["π", "π", "π"];
/**
* 1. Using concat method
*/
const concatFruits = fruits1.concat(fruits2);
console.log("concat:",concatFruits);
/**
* Output
* concat: ["π", "π", "π", "π", "π", "π"]
*/
/**
* 2. Using ES6 spread syntax
*/
const spreadFruits = [...fruits1, ...fruits2];
console.log("spread:",spreadFruits);
/**
* Output
* spread: ["π", "π", "π", "π", "π", "π"]
*/
/**
* 3. Using Push method
* This method will mutate original array [fruits3]
*/
const fruits3 = ["π", "π", "π"];
const fruits4 = ["π", "π", "π"];
const pushFruits = fruits3.push(...fruits4);
console.log("push:",fruits3);
/**
* Output
* push: ["π", "π", "π", "π", "π", "π"]
*/
/**
* 4. Using unshift method
* This method will mutate original array [fruits6]
*/
const fruits5 = ["π", "π", "π"];
const fruits6 = ["π", "π", "π"];
fruits6.unshift(...fruits5);
console.log("unshift:",fruits6);
/**
* Output
* push: ["π", "π", "π", "π", "π", "π"]
*/
/**
* 5. Using splice method
* This method will mutate original array [fruits7]
*/
const fruits7 = ["π", "π", "π"];
const fruits8 = ["π", "π", "π"];
fruits7.splice(3, 0, ...fruits8);
console.log("splice:",fruits7);
/**
* Output
* push: ["π", "π", "π", "π", "π", "π"]
*/