MAP AND FLATMAP METHODS IN JAVASCRIPT
The map() method creates a new array by changing every element of an existing array.
const numbers = [1, 2, 3];
const doubled = numbers.map(number => number * 2);
console.log(doubled); // [2, 4, 6]
1. map()
map() always returns a new array with the same number of elements.
const names = ["sarah", "isaac"];
const upperNames = names.map(name => name.toUpperCase());
console.log(upperNames); // ["ANNA", "MAX"]
2. map() with objects
const users = [
{ name: "Sarah", age: 21 },
{ name: "Isaac", age: 30 },
];
const names = users.map(user => user.name);
console.log(names); // ["Sarah", "Isaac"]
3. flatMap()
flatMap() maps each element and then flattens the result by one level.
const words = ["hello world", "good morning"];
const result = words.flatMap(sentence => sentence.split(" "));
console.log(result); // ["hello", "world", "good", "morning"]
4. map() vs flatMap()
map() = transform each element
flatMap() = transform each element and flatten one level
5. Final summary
map()creates a transformed arraymap()keeps the same number of elementsflatMap()is useful when each item becomes an array