map() in JavaScript :
- map() method creates a new Array by applying a function to each element of the original Array.
- map() returns a new Array of the Same Length.
- map() does not modify the original Array.
Example of returning an Array :
const array = [5, 10, 15, 20];
const newArray = array.map(n => n * 2);
console.log(newArray);
Output :
[ 10, 20, 30, 40 ]
Example of returning nested Array Structure :
const array = [5, 10, 15, 20];
const nestedArray = array.map(n => [n, n * 2]);
console.log(nestedArray);
Output :
[ [ 5, 10 ], [ 10, 20 ], [ 15, 30 ], [ 20, 40 ] ]
Example with null / undefined values in the Array :
const array = ["Hello", null, "World", undefined];
const newArray = array.map(word => word ? [word] : []);
console.log(newArray);
Output :
[ [ 'Hello' ], [], [ 'World' ], [] ]
flatMap() in JavaScript :
- flatMap() method first maps each element using a function, then flattens the result by one level.
- Applies a function like map()
- flattens one level deep of nesting.
- 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 :
const array = [5, 10, 15, 20];
const nestedArray = array.flatMap(n => [n, n * 2]);
console.log(nestedArray);
Output :
[ 5, 10, 10, 20, 15, 30, 20, 40 ]
Example with null / undefined values in the Array :
const array = ["Hello", null, "World", undefined];
const newArray = array.flatMap(word => word ? [word] : []);
console.log(newArray);
Ouput :
[ 'Hello', 'World' ]
NOTE : flatMap() only flattens one level deep.