JavaScript Code


How to append an Array to another Array in JavaScript?


Append an Array to another Array in JavaScript

In this tutorial, you are given two arrays. You should write a JavaScript program to append elements of an array to another array.

Solution

To append an element to an array, we can use JavaScript array method push(). To append all the elements of an array to another, use for loop and recursively add the elements of the array to another array.

Program

Append elements of otherFruits array to the fruits array.

let fruits = ['apple', 'banana', 'cherry'];
let otherFruits = ['mango', 'guava'];

for (let index = 0; index < otherFruits.length; index++) {
    fruits.push(otherFruits[index]);
}

console.log(fruits);



copyright @2022