DEV Community

Cover image for List of ways to merge arrays in javascript!
Varit Patel
Varit Patel

Posted on

List of ways to merge arrays in javascript!

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: ["🍏", "🍎", "🍐", "🍊", "🍋", "🍌"]
 */

Enter fullscreen mode Exit fullscreen mode

Play with jsfiddle

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:

MDN - concat

MDN - Spread

Top comments (0)