;

Javascript Array - concat() Method


Tutorialsrack 26/08/2022 Jquery Javascript

In this article, you’ll learn how to concatenate two or more arrays in javascript. For merging or concatenating two or more arrays in javascript, the javascript array has a built-in array method Array.prototype.concat()

Array.prototype.concat()

The Array concat() method is used to merge two or more arrays in javascript. This method does not change the existing array, rather than it returns a new array. For example

Examples
let arr1 = ["Java", "Javascript", "Python"];
 
let arr2 = ["C#", "ReactJs", "Angular", "Flutter"];
 
// merge two arrays
let concatenatedArray = arr1.concat(arr2);
 
console.log(concatenatedArray)
//Output => ["Java", "Javascript", "Python", "C#", "ReactJs", "Angular", "Flutter"]

This method takes ValueN parameters, which is optional. If all valueN parameters are omitted, then concat() method returns a shallow copy of the existing array on which it is called. For Example,

Examples
let arr1 = ["Java", "Javascript", "Python"];
 
let arr2 = ["C#", "ReactJs", "Angular", "Flutter"];
 
let arr3 = [1, 2, 3];
 
//Javascript Array concat() method without Parameters
console.log(arr1.concat());
//Output => ["Java", "Javascript", "Python"]
 
//Javascript Array concat() method with Parameters
//Merging two array
console.log(arr1.concat(arr2));
//Output =>  ['Java', 'Javascript', 'Python', 'C#', 'ReactJs', 'Angular', 'Flutter']
 
//Javascript Array concat() method with Parameters
//Merging more than two array
//you Can pass multiple arrays as parameters like arr2,arr3,...arrN
console.log(arr1.concat(arr2, arr3));
//Output =>  ['Java', 'Javascript', 'Python', 'C#', 'ReactJs', 'Angular', 'Flutter', 1, 2, 3]

Here are Some more examples of Javascript Array concat() Method:

Examples
const letters = ['a', 'b', 'c'];
const numbers = [1, 2, 3];
const language = ["Java", "Javascript", "Python"];
const nestedArray = [2, 4, 6, [8], [10, 12]]
 
//concatenate two arrays
console.log(letters.concat(numbers));
//Output = > ["a", "b", "c", 1, 2, 3]
 
//Another way concatenate two arrays
console.log([].concat(letters, numbers));
//Output = > ["a", "b", "c", 1, 2, 3]
 
//Concatenate more than two arrays
console.log([].concat(letters, numbers, language));
//Output => ['a', 'b', 'c', 1, 2, 3, 'Java', 'Javascript', 'Python']
 
//Concatenate more than two arrays
console.log([].concat(letters, numbers, language, nestedArray));
//Output => ['a', 'b', 'c', 1, 2, 3, 'Java', 'Javascript', 'Python', 2, 4, 6, [8], [10, 12]]

I hope this article will help you to understand how to concatenate two or more arrays in javascript using Javascript built-in Array.prototype.concat() method.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags