How To Flatten An Array Of Arrays In TypeScript

Flatten an Array of Arrays in TypeScript

If you are looking for the method to flatten an array of arrays in TypeScript, this tutorial is what you need. We will show you how to use the flat() method to do that. Check out the information below for detailed instructions.

Flatten an array of arrays in TypeScript

In this tutorial, we will show you how to use the flat() method for flattening an array of arrays in TypeScript. This method allows us to concatenate sub-array elements, bring these sub-elements to the same depth and return a new array.

Syntax:

const flattenArr = arr.flat(<depth>);  

Parameters:

  • depth: An optional parameter specifies the depth to flatten an array. If you do not declare it, its value defaults to 1.

To illustrate, here is an example:

const cars = [
    ["BMW", "Mercedes"],
    ["Honda", "Toyota"],
    ["Kia", "Hyundai"],
];

const flatten = cars.flat();
console.log(flatten);

Output:

["BMW", "Mercedes", "Honda", "Toyota", "Kia", "Hyundai"]

As you can see, in the above example, we have the array ‘cars’, which is a nested array. Using flat() helped us bring these elements to depth = 1.

Let’s see more examples when the ‘depth’ parameter has a specific value:

const cars = [
    [[["BMW", "Mercedes"]]],
    [[["Honda", "Toyota"]]],
    [[["Kia", "Hyundai"]]],
];

const flatten = cars.flat(2);
console.log(flatten);

Output:

[["BMW", "Mercedes"], ["Honda", "Toyota"], ["Kia", "Hyundai"]]

It can be seen that how much depth we declare, we will have as many [] in the child element.

In case you get the following error message: “Property ‘flat’ does not exist on type ‘string#’. Do you need to change your target library? Try changing the ‘lib’ compiler option to ‘es2019’ or later”, check out the steps below for the solution:

  1. Open the tsconfig.json file.
  2. Find the ‘compilerOptions’ object.
  3. Add ‘es2019’ to the ‘lib’ array.

Your ‘tsconfig.json’ should look like this:

{
  "compilerOptions": {
    "lib": [
      "es2019"
       // ... other settings
    ]
  }
}

At this point, the error seems to be resolved.

Alternatively, you can also use the forEach() method instead of the flat() method. Take a look at the following example:

const cars = [
    ["BMW", "Mercedes"],
    ["Honda", "Toyota"],
    ["Kia", "Hyundai"],
];

const flatten: string[] = [];

cars.forEach((arr) => {
    flatten.push(...arr);
});

console.log(flatten);

Output:

[ 'BMW', 'Mercedes', 'Honda', 'Toyota', 'Kia', 'Hyundai' ]

Function inside the forEach() method will be applied to each element in the array.

We use the push method and spread syntax to unpack the subarray’s values and push them into the new array on each iteration.

We still get the same result as the flat() method in the output. However, we recommend using the flat() method instead because the flat() method is easier to understand and use.

Summary

To sum up, we have shown you how to flatten an array of arrays in TypeScript using the flat() method. You can try practicing on your computer for a better understanding of how this method works. That’s the end of this tutorial. Hopefully, the information we shared will be helpful to you.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *