Difference between map and flatmap in javascript with examples.

map() in JavaScript :

  1. map() method creates a new Array by applying a function to each element of the original Array.
  2. map() returns a new Array of the Same Length.
  3. map() does not modify the original Array.

Example of returning an Array :

Example of returning nested Array Structure :

Example with null / undefined values in the Array :

flatMap() in JavaScript :

  1. flatMap() method first maps each element using a function, then flattens the result by one level.
  2. Applies a function like map()
  3. flattens one level deep of nesting.
  4. useful to remove null/undefined from Array.

Example of returning an Array like map() :

const array = [5, 10, 15, 20];
const newArray = array.flatMap(n => n * 2);
console.log(newArray);

Output :

[ 10, 20, 30, 40 ]

Example of nested structure into a flat Array :

Example with null / undefined values in the Array :

NOTE : flatMap() only flattens one level deep.