How to merge two arrays in angular and typescript?
We will see how to merge one or more arrays using TypeScript. The concat() method returns a new array by concatenating two or more arrays, while the spread operator creates a new array by spreading the elements of the input arrays. We can use the concat() method or the spread operator (…) to merge the arrays; see the examples below.
- Using the concat() method to merge one or more arrays and return to the new array:
let array1 = [1, 2, 3]; let array2 = [4, 5, 6]; let array3 = [7, 8, 9]; let mergedArray = array1.concat(array2, array3); console.log(mergedArray); // [1, 2, 3, 4, 5, 6]
- Using the spread operator to merge the arrays and return the output:
let array1 = [1, 2, 3]; let array2 = [4, 5, 6]; let mergedArray = [...array1, ...array2]; console.log(mergedArray); // [1, 2, 3, 4, 5, 6]
- Using the spread operator to merge the new array with the existing array:
let array1 = [1, 2, 3]; let array2 = [4, 5, 6]; array1.push(...array2); console.log(array1); // [1, 2, 3, 4, 5, 6]
Leave a comment