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)