Javascript array concat method

JavaScript Array.concat() method is used to merge two or more arrays into a new array. This method does not modify the original arrays; instead, it returns a new array that contains the elements of the original arrays..

The syntax for using Array.concat() method is:

array.concat(array1, array2, ..., arrayX)

Here are some examples of how to use the Array.concat() method:

Example 1: Concatenating two arrays:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const result = arr1.concat(arr2);

console.log(result); // [1, 2, 3, 4, 5, 6]

In this example, arr1 and arr2 are two arrays. We use the concat() method to concatenate them into a new array called result. The result array contains all the elements of arr1 followed by all the elements of arr2.

Example 2: Concatenating multiple arrays

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [7, 8, 9];

const result = arr1.concat(arr2, arr3);

console.log(result); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

In this example, we concatenate three arrays arr1, arr2, and arr3 using the concat() method. The result array contains all the elements of arr1, followed by all the elements of arr2, and finally all the elements of arr3.

Example 3: Concatenating arrays with non-array values

const arr1 = [1, 2, 3];
const arr2 = "4, 5, 6";
const arr3 = {a: 7, b: 8, c: 9};

const result = arr1.concat(arr2, arr3);

console.log(result); // [1, 2, 3, "4, 5, 6", {a: 7, b: 8, c: 9}]

In this example, we are concatenating an array arr1 with a string arr2 and an object arr3. The concat() method creates a new array containing all the elements of arr1, followed by the non-array values arr2 and arr3.

Example 4: Using the spread operator for concatenation

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const result = [...arr1, ...arr2];

console.log(result); // [1, 2, 3, 4, 5, 6]

In this example, we are using the spread operator (...) to concatenate two arrays arr1 and arr2. The spread operator expands the elements of each array and creates a new array that contains all the elements of both arrays.

Overall, the Array.concat() method is a useful tool for merging arrays in JavaScript. It allows you to create a new array that contains all the elements of one or more existing arrays.