Transforming Arrays with the map() Method
メニューを表示するにはスワイプしてください
This section covers essential array methods used in everyday coding: map(), filter(), find(), reduce(), and sort(). Let’s start with map().
For a comprehensive list of all array methods, you can refer to the official MDN documentation.
map()
The map() method loops through each element of an array and creates a new array based on the callback function's return value.
array.map((element, index, array) => {
// Callback body
});
element: current item;index: position in the array;array: the original array.
12345const products = ["Ball", "Shoes", "Mouse"]; const modifiedProducts = products.map((element, index, array) => { console.log(`Element: ${element}, Index: ${index}, Array: ${array}`); });
Key points to remember about the map():
- Processes each element;
- Does not modify the original array;
- Returns a new array;
- Resulting array has the same length.
Transforming Array Elements
The map() method shines when we need to transform every element of an array without modifying the original array. Consider the following example:
12345678910const numbers = [3, 5, 11, 32, 87]; /* Use the `map` method to create a new array (`doubledNumbers`) by doubling each element of the `numbers` array. */ const doubledNumbers = numbers.map((element) => { return element * 2; }); console.log("Initial array:", numbers); // Output: 3, 5, 11, 32, 87 console.log("Modified array:", doubledNumbers); // Output: 6, 10, 22, 64, 174
1. What does the map() method do?
2. What is a key characteristic of the map() method?
3. In the example below, what does the strings.map((element) => (element += "!")) do?
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 27
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 1. 章 27