ae4744a771771389bea0
·2 min read

Mastering Array Functions: map and flatMap

javascript
4d5fd787ac74e0caa4f7

Sohan R. Emon

Developer, Learner, Tech Enthusiast

In JavaScript, map and flatMap are two commonly used array methods, and they are used for different purposes. Let's explore the differences between map and flatMap:

  1. map Method:
    • The map method is used to transform the elements of an array by applying a function to each element and creating a new array with the results.
    • The original array remains unchanged, and the resulting array has the same length as the original one.

Here's an example of how you can use map:

javascript
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num * num);

console.log(squaredNumbers); // [1, 4, 9, 16, 25]
console.log(numbers); // [1, 2, 3, 4, 5] (original array is unchanged)
  1. flatMap Method:
    • The flatMap method is used to both map and flatten an array of elements. It applies a function to each element in the array and then flattens the result into a new array.
    • It's particularly useful when you want to map an array of values to an array of arrays and then flatten the result into a single array.
    • flatMap can be thought of as a combination of map and flatten.

Here's an example of how you can use flatMap:

javascript
const words = ['Hello', 'World'];
const letters = words.flatMap(word => word.split(''));

console.log(letters); // ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']

In summary, map is used for mapping or transforming elements in an array, creating a new array with the same length, while flatMap is used for mapping and flattening, which may result in a different array length.

Your choice between map and flatMap depends on the specific task you want to perform on the elements in the array.

Found this useful?