DEV Community

Cover image for Understanding flatMap() and other TypeScript arrays
Matt Angelosanto for LogRocket

Posted on • Originally published at blog.logrocket.com

Understanding flatMap() and other TypeScript arrays

Written by Muhammed Ali✏️

Arrays are an essential part of TypeScript, allowing developers to store and manipulate data collections. The Array object comes with various methods that make it easy to work with arrays. One such method is the flatMap() method.

In this article, we'll explore what flatMap() is and how it works. We’ll also explain how to declare an array in TypeScript and provide a list of other useful array methods available in TypeScript, like concat(), copyWithin(), every(), fill(), filter(), flat(), forEach(), shift(), includes(), and reduce(). Let’s get started!

Jump ahead:

What is flatMap()?

The flatMap() method is available on the Array object in TypeScript. It works similarly to the map() method but with one key difference. Not only does the flatMap() method map each element of an array to a new value, but it will also flatten that array and add its element to the resulting array.

Why should you use flatMap()?

flatMap() takes a multi-dimensional array and compresses it into a single list of values, combining the ability of map() to modify the content of an array.

To fully understand what flatMap() does, you first have to have an idea of what flat() does. Flattening an array removes all the nested arrays, leaving only a single-level array that contains all the elements of the original array. Basically, the flat() method is equivalent to using myArray.map.flat().

How to declare an array in TypeScript

To declare an array in TypeScript, you can use either the square brackets notation or the Array keyword.

Using square brackets notation

With the square brackets notation, the array name is labelled using arrayName. elementType is the data type of the elements that will be stored in the array, taking in number, string, or boolean. The square bracket [] is used to indicate that the variable is an array:

const arrayName:elementType[]=[element1,element2,...];
Enter fullscreen mode Exit fullscreen mode

In the example below, myArray is a variable type, number[], and it is initialized with an array of numbers:

const myArray:number[]=[1,2,3,4,5]
Enter fullscreen mode Exit fullscreen mode

Using the Array keyword

In the example below, myArray is a variable of type Array<string>, which is the array of the string:

const myArray:Array<string>=['goat','sheep','ram']
Enter fullscreen mode Exit fullscreen mode

Using flatMap() in TypeScript

Let's use flatMap() to compress the code into a single list, where every entry in the array is a single movie title:

const Movies: (string | string[])[] = [
    'Dog Soldiers',
    ['In Bruges', 'From Paris with Love'],
    'The Big Lebowski',
    'The Platform',
    'Fight Club',
    'Hotel Rwanda',
    'Moon',
    'Hulu Originals',
    'Lady Bird',
    'Platoon',
    'Wall-E',
  ];
    // declares a new array of strings called movieTitles
    // use the flatMap method on the Movies array
 const movieTitles: string[] = Movies.flatMap((movie) =>
  // if the element is an array, flatten it, otherwise wrap it in an array
Array.isArray(movie) ? movie : [movie]
  );

  console.log(movieTitles); 
// Output: ["Dog Soldiers", "In Bruges", "From Paris with Love", "The Big Lebowski", "The Platform", "Fight Club", "Hotel Rwanda", "Moon", "Hulu Originals", "Lady Bird", "Platoon", "Wall-E"]                                  
Enter fullscreen mode Exit fullscreen mode

The example code above creates an array called movieTitles, which contains all the movie titles from the Movies array. The Movies array may contain nested arrays of strings, which represent movies with multiple titles. To ensure that each movie title is represented as a single string, we use the flatMap() method to flatten the nested arrays within the Movies array.

The flatMap() method takes a callback function as an argument, which checks whether the current element of the array is an array itself using the Array.isArray() method. If the current element is an array, flatMap() flattens it into a single array of strings.

If the current element is already a string, the callback function returns it as a single-item array. The resulting array of arrays is then flattened into a single array of strings using flatMap().

After running the code above, you’ll see the following error:

Error: Property flatMap does not exist on the type (string|string [])[].
Enter fullscreen mode Exit fullscreen mode

To fix this error, you'll need to add the string "es2019" to the lib array in your tsconfig.json file. The "lib" option specifies the libraries that are available to your TypeScript code during compilation. By default, TypeScript targets the "ES5" version of JavaScript, which doesn’t include the flatMap() method.

Therefore, you'll need to specify a later version of JavaScript that includes this method. You can do so by adding the "es2019" string to the "lib" array in your tsconfig.json file. This will make the flatMap() method available to your TypeScript code during compilation, and the error should be resolved.

The example below shows what the "lib" array in your tsconfig.json file will look like after adding "es2019":

//tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["es2019", "dom"]
  }
}
Enter fullscreen mode Exit fullscreen mode

You can also test out the code using TypeScript playground.

Different types of arrays in TypeScript

In addition to flatMap(), TypeScript provides many other useful array methods, including:

  • concat()
  • copyWithin()
  • every()
  • fill()
  • filter()
  • flat()
  • forEach()
  • shift()
  • includes()
  • reduce()

concat()

In TypeScript, we can use the concat() method to join two or more arrays and return a new array that contains all the elements of the original arrays:

 const array1:string[]=['monkey','ape','gorilla']
  const array2:string[]=['goat','sheep','ram']
  const newArray: string[]=array1.concat(array2)
  console.log(newArray);
//Output:['monkey','ape','gorilla','goat','sheep','ram']
Enter fullscreen mode Exit fullscreen mode

In the example code above, we have two arrays, array1 and array2. We use the concat() method on array1 and pass array2 as an argument. The concat() method returns a new array that contains all the elements of array1 and array2. We then assign a new array to a variable called newArray and log it to the console.

copyWithin()

copyWithin() is a built-in method that allows us to copy the same array elements within the same array. The copyWithin() method modifies the original array and returns a reference to the modified array:

const array:number[]=[1,2,3,4,5];
array.copyWithin(0,3,5);
console.log(array)
//Output[4,5,3,4,5,]
Enter fullscreen mode Exit fullscreen mode

copyWithin() copies the element from index 3 to index 5 of the array to the position starting from index 0. So, the elements at indexes 3 and 4 are copied to the positions starting from index 0. The code above shows the resulting array.

every()

To check if all elements in an array pass a test, we can use TypeScript's every() method. It returns a boolean value, true or false:

const array:number[]=[1,2,3,4,5,6,7,8,9,10,11]
const allEven=array.every((num)=>num%2 === 0);
console.log(allEven)
//Output:false
Enter fullscreen mode Exit fullscreen mode

In our example above, the every() method checks if all elements in the array are even numbers. The callback function (num)=>num % 2===0 checks if the remainder of each element divided by 2 is 0, which is even. Since there are odd numbers in the array, every method returns false and assigns it to the allEven variable.

fill()

With the fill() method, you can fill all the elements of an array from a start index to an end index with a static value:

const arr:string[]=['python','java','golang','ruby','reactjs']
//this fill the array for the index 1 and index 2 with the value 'css'
arr.fill('css', 1,3); // doesn't include index 3 when filling
console.log(arr);
//Output:['python','css','css','ruby','reactjs']
Enter fullscreen mode Exit fullscreen mode

We declare an array arr of the type string[], meaning it can only contain strings. We then use the fill() method to fill the array for index 1 and index 2 with the value css. Finally, we log the updated array to the console.

filter()

We use the filter() method to create a new array that contains all the elements of an existing array that pass a certain test or meet a certain condition. The filter() method doesn’t modify the original array, but instead, it returns a new array with the filtered elements:

const arr: string[] = ['band', 'shoe', 'skirt', 'bag'];

// Filter the array to only include strings that start with 'b'
const filteredArr = arr.filter((str) => str.startsWith('b'));

console.log(filteredArr); // Output: ['band','bag']
Enter fullscreen mode Exit fullscreen mode

We declare an array arr of type string[] with five-string elements. We then use the filter() method to create a new array, filteredArr, which only includes the strings from arr that start with the letter b.

We use an arrow function as the argument to the filter() method to define the conditions for filtering the array. We then log the filteredArr to the console, which in this case, will only contain the string band and bag.

flat()

In TypeScript, the flat() method is available on arrays and can be used to create a new, one-dimensional flattened array. flat() can take an optional argument that specifies the depth of flattening. If no argument is provided, flat() will flatten the array to a depth of 1:

const arr = ["Hello", ["World", "!"]];
const flattened = arr.flat();
console.log(flattened); 
// Output: ["Hello", "World", "!"]
Enter fullscreen mode Exit fullscreen mode

We have an array, arr, that contains a nested array of strings. We call the flat() method on the arr array, which flattens the array to a depth of 1, resulting in a new array with the same elements, but flattened to a one-dimensional array of strings. The flat() method works the same way on an array of any type, not just on an array of strings.

forEach()

We can use the TypeScript forEach() method on an array of strings to iterate over each string in the array and perform a specified action on that string:

const arr:string[]=['goat','sheep','ram'];
arr.forEach((items:string)=>{
    console.log(items)
});
//Output:goat
//        sheep
 //       ram
Enter fullscreen mode Exit fullscreen mode

The code above declares a constant array of strings named arr with three elements: goat, sheep, and ram. The forEach method is then called on the arr array, which iterates through each element of the array and executes the provided function once per element.

shift()

In TypeScript, shift() is used to delete the first value from an array and then return the remaining values:

let arr: number[] = [1, 2, 3, 4, 5];
let firstElement: number | undefined = arr.shift();

console.log(firstElement); // Output: 1
console.log(arr); // Output: [2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

We define the arr variable as an array of numbers using the number[] syntax. We've also defined the first element variable as a union type of number | undefined because shift() can return undefined if the array is empty. When calling shift(), we don't need to specify any arguments. It simply removes the first element from the array.

includes()

The TypeScript includes() method checks if an array contains a particular value among its elements, returning true or false where suitable:

let arr: string[] = ['goat','sheep','ram'];
console.log(arr.includes('goat')); // Output: true
console.log(arr.includes('cow')); // Output: false
Enter fullscreen mode Exit fullscreen mode

In the code above, we've defined the arr variable as an array of strings. We then use the includes() method to check whether the array contains the string goat or the string cow. The method returns true for the former and false for the latter.

reduce()

reduce() is a built-in method of the Array object. We can use it to reduce an array to a single value by applying a function to each element of the array:

let arr: number[] = [1, 2, 3, 4, 5];
let sum: number = arr.reduce((accumulator: number, currentValue: number) => {
  return accumulator + currentValue;
});
console.log(sum); // Output: 15
Enter fullscreen mode Exit fullscreen mode

In the code, we've defined the arr variable as an array of numbers. We then use the reduce() method to calculate the sum of all the numbers in the array.

The reduce() method takes two arguments: a callback function and an optional initial value. In this case, we've only provided the callback function. The callback function takes two arguments. The first is an accumulator that stores the current state of the reduction, and the second is the current value of the array being processed. The function returns the updated value of the accumulator.

In the example, we start with an initial value of 0 for the accumulator. On each iteration of the reduce() method, the callback function adds the current element to the accumulator, which stores the sum of all the elements in the array. The final value of the accumulator is returned as the final output of the reduce() method, which is stored in the sum variable and printed to the console.

Conclusion

In this article, we explored the TypeScript  flatMap() method, learning how it simplifies code that involves mapping and flattening arrays. By understanding how to effectively use flatMap(), you can improve your code and make it more efficient.

We also briefly discussed arrays in TypeScript, providing examples of different types of arrays. Understanding how to declare and work with arrays is a fundamental skill in TypeScript programming, and it's essential for building complex applications. I hope you enjoyed this article, and be sure to leave a comment if you have any questions. Happy coding!


Get setup with LogRocket's modern TypeScript error tracking in minutes:

1.Visit https://logrocket.com/signup/ to get an app ID.
2.Install LogRocket via NPM or script tag. LogRocket.init() must be called client-side, not server-side.

NPM:

$ npm i --save logrocket 

// Code:

import LogRocket from 'logrocket'; 
LogRocket.init('app/id');
Enter fullscreen mode Exit fullscreen mode

Script Tag:

Add to your HTML:

<script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script>
<script>window.LogRocket && window.LogRocket.init('app/id');</script>
Enter fullscreen mode Exit fullscreen mode

3.(Optional) Install plugins for deeper integrations with your stack:

  • Redux middleware
  • ngrx middleware
  • Vuex plugin

Get started now

Top comments (0)