Skip to main content

Exercise 23: Multiplying Array Elements by 2 with map()

Learn how to use the map() method in JavaScript to iterate through an array and easily duplicate each of its elements. The main objective is to learn how to use this method.map()to transform each element of an array.

Activity

  1. Create an array containing numbers from 1 to 5.

  2. Usemap()To create a new array where each element is double the original number.

  3. Print the original array and the new array to the console.

Solution

Step 1: Create the index.html file

HTML
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Multiplicar Elementos de un Array por 2 con map()</title>
</head>
<body>
<h1>Ejercicio 23: Multiplicar Elementos de un Array por 2 con map()</h1>
<p>Los cambios se muestran en consola.</p>
<script src="script.js"></script>
</body>
</html>

Step 2: Write the code in script.js

JavaScript
const numeros = [1, 2, 3, 4, 5];

const numerosMultiplicados = numeros.map((numero) => numero * 2);

console.log("Array original:", numeros);
console.log("Array multiplicado por 2:", numerosMultiplicados);
info

🔎Check the sectionArray methods in JavaScriptwhere you will find more information on this topic.