DEV Community

Cover image for Here are a few ways to merge array
Dhairya Shah
Dhairya Shah

Posted on • Originally published at codewithsnowbit.hashnode.dev

Here are a few ways to merge array

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"]
Enter fullscreen mode Exit fullscreen mode

Merging Arrays with the concat() method

concat()

  • 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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • 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++){
   fruitsOne.push(fruitsTwo[i])
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ
const mergedFruits = [...fruitsOne, ...fruitsTwo]
Enter fullscreen mode Exit fullscreen mode