Advertisement
xerocool-101

004 map method

Apr 20th, 2025 (edited)
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 0.67 KB | Software | 0 0
  1. // The .map() method creates a new array by applying a function to each element of the original array.
  2. // It's like saying: “take each item, do something to it, and return a new array with the results.”
  3.  
  4. // Return new array
  5. const numbers = [1, 2, 3, 4];
  6. const doubled = numbers.map((num, index, array) => num * 2);
  7. console.log(doubled); // [2, 4, 6, 8]
  8.  
  9. // Object
  10. const users = [
  11.   { id: 1, name: "Alice" },
  12.   { id: 2, name: "Bob" }
  13. ];
  14.  
  15. const names = users.map(user => user.name);
  16. console.log(names); // ["Alice", "Bob"]
  17.  
  18. // React
  19. setUsers(users.map((u) => (u._id === editId ? res.data : u)));
  20.  
  21. {todos.map(todo => (
  22.   <li key={todo.id}>{todo.text}</li>
  23. ))}
  24.  
  25. //
  26.  
Tags: JavaScript
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement