Well, Imagine interviewer ask you to tell the ways to merge two arrays in JavaScript? There are various ways you can achieve it. so in this post, we will go through some of the ways to merge arrays.
Let's see some ways!
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: ["π", "π", "π", "π", "π", "π"]
*/
Based on the above implementation, Recommend and convenient ways are
- option 1: Array.prototype.concat()
method or
- option 2: Spread syntax
Feel free to comment if you know any other way to do so.
References:
Top comments (0)