23 Feb 2024




Intermediate

In JavaScript, both map and flatMap are higher-order functions that are commonly used with arrays to transform and manipulate their elements. While they are similar in that they both iterate over an array, they serve slightly different purposes and have different behaviors.

  • map():

    • The map() method creates a new array by calling a specified function on each element in the original array.
    • It does not change the original array.
    • The function passed to map() is applied to each element of the array, and the return value of the function is used as the corresponding element in the new array.
    • If the function returns an array for each element, map() will result in an array of arrays, which might not be the desired outcome.

    Example:

    const people = [
      { name: 'Alice', hobbies: ['reading', 'painting'] },
      { name: 'Bob', hobbies: ['swimming', 'cooking'] },
      { name: 'Charlie', hobbies: ['running', 'gardening'] }
    ];
    

    Using map():

    const allHobbiesMapped = people.map(person => person.hobbies);
    console.log(allHobbiesMapped);
    

    Output:

    [
      ['reading', 'painting'],
      ['swimming', 'cooking'],
      ['running', 'gardening']
    ]
    

    Here, map() creates a new array where each element is an array of hobbies for each person. However, we end up with an array of arrays.

  • flatMap():

    • The flatMap() method is similar to map(), but it first maps each element using a mapping function, and then flattens the result into a new array. It basically combines map() and flat() into one method.
    • It allows you to both map and flatten in a single step.
    • It is particularly useful when you want to map each element to an array and then flatten the arrays into a single array.
    • If the function passed to flatMap() returns an array for each element, flatMap() will automatically flatten the result.

    Example:

    const people = [
      { name: 'Alice', hobbies: ['reading', 'painting'] },
      { name: 'Bob', hobbies: ['swimming', 'cooking'] },
      { name: 'Charlie', hobbies: ['running', 'gardening'] }
    ];
    

    using flatMap():

    const allHobbiesFlatMapped = people.flatMap(person => person.hobbies);
    console.log(allHobbiesFlatMapped);
    

    Output:

    ['reading', 'painting', 'swimming', 'cooking', 'running', 'gardening']
    

    With flatMap(), we directly get a flattened array containing all hobbies. It automatically flattens the result for us, resulting in a single array of hobbies.

Summary: while map() is used for simple one-to-one transformations of elements in an array, flatMap() is used when you need to both map and flatten the result, especially when dealing with nested arrays or arrays of arrays.

javascript
map
flatmap