How to useArray.prototype.concat and apply in Typescript

This method uses the concat method along with apply to flatten the array. It essentially spreads the elements of the nested arrays into a new array.

Example: In this example, We use the concat method along with apply to flatten the nested array. The concat method is employed to concatenate the arrays, and apply spreads the elements of the nested arrays into a new array.

Javascript
const nestedArray: number[][] = [[1, 2], [3, 4], [5, 6]];
const flattenedArray: number[] = [].concat.apply([], nestedArray);

console.log(flattenedArray);

Output:

[1, 2, 3, 4, 5, 6] 

How to Flatten Array of Arrays in TypeScript ?

Array flattening is the process of converting a nested array (an array of arrays) into a single-dimensional array where all the elements are at the same level. In other words, it involves transforming an array that contains other arrays as elements into an array that only contains non-array elements.

Array flattening is commonly needed when dealing with arrays of arrays, especially when you want to simplify the data structure for easier processing or when working with functions that expect a flat array as input.

Example:

Before Flattening Array of Arrays
const nestedArray: number[][] = [[1, 2], [3, 4], [5, 6]];
After Flattening Array of Arrays
const flattenedArray: number[] = [1, 2, 3, 4, 5, 6];

Below are the approaches used to Flatten array of arrays in TypeScript:

Table of Content

  • Using Array.prototype.concat and apply
  • Using Array.prototype.reduce
  • Using Array.prototype.flat
  • Using ForEach
  • Using the spread operator and Array.prototype.push

Similar Reads

Approach 1: Using Array.prototype.concat and apply

This method uses the concat method along with apply to flatten the array. It essentially spreads the elements of the nested arrays into a new array....

Approach 2: Using Array.prototype.reduce

The reduce method is used here to iterate over the nested arrays and accumulate their elements into a single array....

Approach 3: Using Array.prototype.flat

The flat method is a built-in JavaScript method that can be used to flatten an array by a specified depth....

Approach 4: Using ForEach

To flatten an array of arrays in TypeScript using forEach, you can iterate over each element of the outer array and then use another forEach loop to handle the inner arrays....

Approach 5: Using the spread operator and Array.prototype.push

In this approach, we utilize the spread operator to spread the elements of each inner array into a new array. We then use the push method to add each element from the spread array to the resulting flattened array....

Contact Us