How to Append One Array to Another Array in Javascript
In this tutorial, you will learn how to append one array to another array in javascript. An array is nothing more than a collection of items and in your project, you can have multiple arrays.
Appending one array to another array can be tricky. There are multiple solutions to this problem. A common solution for this problem is using the concat()
method. But it does not fulfill our requirement since the concat()
method returns a completely new array.
We are going to use a combination of the push()
method and spread
operator to accomplish our goal. In the following example, we have 2 arrays and upon click of a button, I want to merge the second array to the first one and display all items in the array on the webpage. Please have a look over the code example and steps given below.
HTML & CSS
- We have 3 elements in the HTML file (
div
,button
, andul
). Thediv
element is just a wrapper for the rest of the elements. - The
button
element has“Update”
as inner text. - The
ul
element does not have any child elements. We will populate it by javascript. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div> <button>Update</button> <ul></ul> </div> <script src="script.js"></script> </body> </html>
div { margin: auto; width: 10%; } button{ padding: 10px; display: inline-block; } li { font-size: 20px; font-weight: bold; margin-left: -40px; list-style: none; }
Javascript
- We have 2 global variables
fruits1
andfruits2
. They both hold an array of fruit names. - We have created the
addFruits()
method and executed it in the next line. This method is responsible for creating a template string ofli
elements by looping throughfruits1
array and setting that template string asinnerHTML
oful
element. - We have selected
button
element usingdocument.querySelector()
and stored it in thebtnUpdate
variable. - We have attached the
click
event listener to thebutton
element. - In the event handler function, we are calling the
push()
method on thefruits1
array and passingfruits2
array as a parameter but before that, we are spreading it using thespread
operator.
let fruits1 = ['Apple', 'Orange', 'Mango']; let fruits2 = ['Kiwi', 'Grapes', 'Banana']; function addFruits(){ let template = fruits1.map(fruit => `<li>${fruit}</li>`).join('\n'); document.querySelector('ul').innerHTML = template; } addFruits(); let btnUpdate = document.querySelector('button'); btnUpdate.addEventListener('click', () => { fruits1.push(...fruits2); addFruits(); });