Array.concat() method

The concat method is used to create a new array with the elements of the passed arrays or the values. It adds the elements at any index of the array.

Features:

  • It allows to passing of multiple arrays of values as an argument to it.
  • It can merge the nested arrays as well to create a flattened array.
  • It allows to merge the arrays with mixed or different data types.
  • It also works efficiently with the arrays of generic types in TypeScript.
  • It can be used in a chain of methods with other methods as well.

Syntax:

const newArrayName = arr1.concat(arr2);

Example: The below code example implements the concat() method in TypeScript.

Javascript




const arr1: number[] = [1, 2, 3];
const arr2: string[] =
    ["TypeScript", "w3wiki", "JavaScript"];
const mergedArray: (number | string)[] =
    arr1.concat(arr2);
console.log(mergedArray);
const newMergedArray: (number | string)[] =
    mergedArray.concat(4, 5, ["GFG"]);
console.log(newMergedArray);


Output:

[1, 2, 3, "TypeScript", "w3wiki", "JavaScript"]
[1, 2, 3, "TypeScript", "w3wiki", "JavaScript", 4, 5, "GFG"]

Difference Between Spread Operator and Array.concat() in Typescript

The spread operator and concat() method both are used to add elements to an array. But they are different from each other in many ways. Let us discuss the difference between both of them in detail.

Similar Reads

Spread Operator

The spread operator creates a new array by merging the elements of the passed arrays or the values. It is denoted by three dots(…). It unpacks the elements of the passed arrays and creates a new array with the elements of both the passed arrays....

Array.concat() method

...

Difference between the Spread operator and concat() method

The concat method is used to create a new array with the elements of the passed arrays or the values. It adds the elements at any index of the array....