Created
April 29, 2025 12:56
-
-
Save sejalkailashyadav/33ec25cee71f95c92dcc98424584ca02 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### ✅ You can use `map()` on: | |
1. **An array of values** | |
2. **An array of objects** | |
3. **An array of arrays** | |
Basically, any array. | |
--- | |
### 🔹 1. **Array of values** | |
```js | |
const numbers = [1, 2, 3]; | |
const squared = numbers.map(num => num * num); | |
console.log(squared); // [1, 4, 9] | |
``` | |
--- | |
### 🔹 2. **Array of objects** | |
```js | |
const users = [ | |
{ name: "Alice", age: 25 }, | |
{ name: "Bob", age: 30 } | |
]; | |
const names = users.map(user => user.name); | |
console.log(names); // ["Alice", "Bob"] | |
``` | |
--- | |
### 🔹 3. **Array of arrays** | |
```js | |
const matrix = [[1, 2], [3, 4]]; | |
const doubled = matrix.map(arr => arr.map(x => x * 2)); | |
console.log(doubled); // [[2, 4], [6, 8]] | |
``` | |
--- | |
<!-- Great! Here's a hands-on JavaScript exercise to help you practice both `map()` and `flatMap()`. | |
--- | |
### **Exercise: Get all comment texts from blog posts** | |
#### Given this data: | |
```js | |
const blogPosts = [ | |
{ | |
title: "Post 1", | |
comments: [ | |
{ user: "Alice", text: "Great post!" }, | |
{ user: "Bob", text: "Thanks for sharing." } | |
] | |
}, | |
{ | |
title: "Post 2", | |
comments: [ | |
{ user: "Charlie", text: "Interesting read." } | |
] | |
} | |
]; | |
const allEmployeeNames = blogPosts.flatMap(blog => | |
dblog.comments.map(t => t.nametext) | |
); | |
console.log(allEmployeeNames); | |
``` | |
--- | |
### Task 1: | |
Use **`map()` + `flat()`** to get an array of **all comment texts**. | |
**Expected Output:** | |
```js | |
const allEmployeeNames = blogPosts.flatMap(blog => | |
blog.comments.map(t => t.text) | |
); | |
["Great post!", "Thanks for sharing.", "Interesting read."] | |
``` | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment