Here are a few ways to merge array

Here are a few ways to merge array


2 min read

Hello Folks ๐Ÿ‘‹

What's up friends, this is SnowBit here. I am a young passionate and self-taught frontend web developer and have an intention to become a successful developer.

Today, I am here with a simple but important topic in JavaScript. In this article, I will discuss a few ways to merge arrays that you can use while merging arrays in your next project.

๐ŸŒŸ Introduction

Arrays are an ordered list, each value in an array is called element specified by an index. An array can store data in the following types:

  • numbers
  • string
  • boolean
const fruits = ["Apple", "Mango", "Orange", "Strawberry"]

Merging Arrays with the concat() method


  • concat() method joins two or more arrays and returns a new array containing joined arrays without changing the original arrays.
const fruitsOne = ["Apple", "Mango"]
const fruitsTwo = ["Orange", "Strawberry"]

const fruits = fruitsOne.concat(fruitsTwo)

Merging with push() method

  • The push method adds elements to the end of the existing array.
  • Here, the items of an array is pushed to the original array which updates the original array.
  • One can merge array using the push() method in two ways: 1) Using spread operator and 2) using for loop.

  • Spread operator is the more preferred method since it keeps code clean and more efficient.

fruitsOne.push(...fruitsTwo) // Spread Operator Method
  • One can either use for loop; I don't suggest you to use that, for your knowledge I am showing the method.
for(let i = 0; i < fruitsTwo.length; i++){

So, this was it for this article, I hope this article helped you.

Thank you for reading, have a nice day!

Your appreciation is my motivation ๐Ÿ˜Š - Give it a like