TypeScript Array map() vs flatMap(): Whats’s Difference?

The map() and flatMap() operations are part of built-in Array type of TypeScript that represents a collection of items. This tutorial discusses the syntax, simple examples and noticeable differences between the Array’s map() and flat() operations.

const sentencesArray: string[] = ["good morning", "good afternoon"];

// Using map() for one-to-one transformation
// Output: ["GOOD MORNING", "GOOD AFTERNOON"]   
const upperCaseSentences: string[] = sentencesArray.map(sentence => sentence.toUpperCase());

// Using flatMap() for one-to-many and flatten transformation
// Output: ["good", "morning", "good", "afternoon"] 
const allWordsArray = sentencesArray.flatMap(sentence => sentence.split(" "));

1. A Quick Recap of TypeScript Arrays

Similar to other programming languages, arrays provide a structured way to store and manage collections of data in TypeScript. Compared to JavaScript, TypeScript arrays offer more power with type checking and additional features.

In TypeScript, we can create arrays in several ways:

// Using array literals
const numArray: number[] = [1, 2, 3, 4, 5];

// Using the Array constructor
const fruitsArray: Array<string> = new Array("apple", "banana", "orange");

Arrays store elements with zero-based indexing, which allows to retrieve, modify and delete elements using the index locations.

console.log(fruitsArray[0]); // Output: "apple"
console.log(fruitsArray[1]); // Output: "banana"

Additionally, TypeScript Array type provides additional methods to retrieve, add, update, delete and process the elements stored in the array. Some of the commonly used operations are:

  • push(): Adds one or more elements to the end of an array.
  • pop(): Removes and returns the last element from an array.
  • concat(): Concatenate the specified array to the original array.
  • slice(): Creates a new array containing elements within the specified range.
  • splice(): Changes the content of an array by removing, replacing, or adding elements.
  • map(): Creates a new array by applying a provided function to each element of the original array.
  • flatMap: Maps each element using a mapping function, then flattens the result into a new array.
  • filter: Creates a new array containing all elements that pass the provided testing function.
  • reduce(): Applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
  • every(): Tests whether all elements in the array pass the provided testing function.
  • sort(): Sorts the elements of an array in place and returns the sorted array.
const fruitsArray: Array<string> = new Array("apple", "banana", "orange");

// Using push() to add elements to the end of the array
fruitsArray.push("grape", "kiwi");
console.log(fruitsArray); // Output: ["apple", "banana", "orange", "grape", "kiwi"]

// Using pop() to remove and return the last element from the array
const removedFruit = fruitsArray.pop();
console.log(removedFruit); // Output: "kiwi"
console.log(fruitsArray);  // Output: ["apple", "banana", "orange", "grape"]

// Using filter() to create a new array containing elements with "a"
const filteredFruits = fruitsArray.filter(fruit => fruit.includes("a"));
console.log(filteredFruits); // Output: ["apple", "banana", "orange"]

In the next sections, we will explore more on the methods map() and flatMap().

2. TypeScript Array map(): One-to-One Transformation

Now that we have a good understanding of the ArrayType, let us understand more about the map() operation.

2.1. Description

By definition, the map() operation transforms each element in this array and returns a new array containing the transformed elements. Here, transformation is essentially a function or operation that is performed on each element of the array, one at a time.

The most important thing to note is that for each input element from the original array, there is one output element in the resulting array. Even the ordering of elements in the input array and the output array is maintained.

2.2. Example – Transform the Element Values

Consider the following example of an array containing the numbers. We want to find out the square of each number in the array and store the results in a new array.

const numbers: number[] = [1, 2, 3, 4, 5];

// Using map() to sqaure each number and store in new array
const sqauredNumbers: number[] = numbers.map(num => num * num);

console.log(sqauredNumbers); // Output: [1, 4, 9, 16, 25] 

2.2. Example – Map Array Elements to Another Type

We can use the map() operation to transform the array elements from one type to another type.

In the following example, we have an array of Person types. We want to get the full name of all persons by combining the first name and last name of each person. In the resulting array, we will have elements of string types.

interface Person {
  firstName: string;
  lastName: string;
}

const people: Person[] = [
  { firstName: "John", lastName: "Doe" },
  { firstName: "Jane", lastName: "Smith" },
  { firstName: "Bob", lastName: "Johnson" },
];

// Using map to transform the array of people into an array of full names
const fullNames: string[] = people.map(person => `${person.firstName} ${person.lastName}`);

console.log(fullNames); 
// Output: ["John Doe", "Jane Smith", "Bob Johnson"]

We can see that there is a one-to-one correspondence between input elements and output elements, and the order is also the same.

3. TypeScript Array flatMap(): One-to-Many Transformation

3.1. Description

The most important thing to notice is that flatMap() operation follows a one-to-many transformation. It applies a mapping function to each element of the array and flattens the resulting array of arrays into a single resulting array.

When we use the flatMap() operation, the following happens:

  • It takes an element from the original array and applies the mapping function.
  • The mapping function returns an array of output values.
  • The resulting arrays from the mapping function are flattened into a single resulting array.

3.2. Example

For example, we can implement a word-counting program using flatMap() in TypeScript. The following program takes an array of sentences, splits them into words, and then counts the occurrences of each word.

const sentencesArray: string[] = [
    "hello world",
    "good morning",
    "good afternoon",
    "beautiful world"
];

const wordsCount: Map<string, number> = new Map();

const flattenedArray = sentencesArray
    .flatMap(sentence => sentence.split(" "));

//Outputs ["hello", "world", "good", "morning", "good", "afternoon", "beautiful", "world"] 
console.log(flattenedArray);

flattenedArray.forEach(word => {
    const count = wordsCount.get(word) || 0;
    wordsCount.set(word, count + 1);
});

// Outputs {"hello" => 1, "world" => 2, "good" => 2, "morning" => 1, "afternoon" => 1, "beautiful" => 1}
console.log(wordsCount);

In the above example, the flatMap() operation:

  • Takes an element from the sentencesArray which is the input element.
  • Splits the sentence into words, which returns an array containing all the words in that sentence.
  • Finally, it flattens all the word arrays and returns a single array containing all the words from all the arrays.

4. Difference between map() and flatMap() Operations

Now, we have good understanding of map() and flatMap() operations, lets compare them side by side:

Aspectmap()flatMap()
PurposeThe callback function can return any value.Transforms each element from the input array and flattens the result.
TransformationReturns a 1-to-1 transformed array.Returns a 1-to-many transformed and flattened array.
Return TypeReturns an array of the same length as the original.Returns an array that can be shorter or longer.
FlatteningDoes not flatten nested arrays.Automatically flattens nested arrays.
Use CaseMapping elements while maintaining array length and element’s order.Mapping and flattening nested arrays.

5. Conclusion

In conclusion, we can say that the map() and flatMap() operations are very useful Array methods that allow us to manipulate and transform arrays in unique ways. Both methods serve distinct purposes and so can be used in data processing tasks.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode