Contenido del Curso
JavaScript Data Structures
JavaScript Data Structures
map() Method
This section will explore several commonly used methods for working with arrays in JavaScript. JS offers a wide variety of methods, but we will focus specifically on those that prove invaluable in everyday programming: map()
, filter()
, find()
, reduce()
, and sort()
. These methods are chosen for practical utility, addressing common scenarios encountered in coding tasks.
For a comprehensive list of all array methods, you can refer to the official MDN documentation.
map()
The map()
method iterates over each element of the original array and applies a specified callback function to produce a new array.
Here's the basic syntax:
element
: This is the current element being processed in the array;index
: This is the current element's index within the array. It represents the position of the element in the array;array
: This is the array on which themap()
method was called. It refers to the original array being iterated over.
Let's illustrate what element
, index
, and array
represent:
const 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():
- It iterates over the original array element by element;
- It does not modify the original array;
- The callback function's result is used to create a new array;
- It returns a new array of 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:
const 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
¡Gracias por tus comentarios!