Array methods · Métodos de arrays
Array methods
.map(fn)makes a new array by transforming each item..filter(fn)makes a new array of only the items wherefnreturnstrue..forEach(fn)runsfnfor each item, making no new array.
Métodos de array
.map(fn)crea un nuevo array transformando cada elemento..filter(fn)crea un nuevo array con solo los elementos para los cualesfndevuelvetrue..forEach(fn)ejecutafnpara cada elemento, sin crear ningún nuevo array.
let nums = [1, 2, 3];
let doubled = nums.map((n) => n * 2);
console.log(doubled); // → [2,4,6]
Filtering keeps some items
.filterkeeps each item for which the test returnstrue.
Filtrar mantiene algunos elementos
.filtermantiene cada elemento para el cual la prueba devuelvetrue.
let nums = [3, 7, 2, 9];
let big = nums.filter((n) => n > 4);
console.log(big); // → [7,9]
Watch out
.mapand.filterreturn a new array — the original is untouched.- You hand each one an arrow function that says what to do with one item.
Precaución
.mapy.filterdevuelven un nuevo array — el original permanece intacto.- Pasas a cada uno una función de flecha que indica qué hacer con un elemento.
Common mistakes
mapandfilterreturn a NEW array — they do not change the original.forEachjust loops and returns nothing.
Errores comunes
mapyfilterdevuelven un NUEVO array — no modifican el original.forEachsimplemente itera y no devuelve nada.
Now you try
- Use
.map,.filteror.forEach. - Press Check answer to test it.
Ahora tú lo intentas
- Usa
.map,.filtero.forEach. - Pulsa Comprobar respuesta para verificarlo.
Use .map to double every number in [1, 2, 3] and store the new array in result (it should be [2, 4, 6]). · Usa .map para duplicar cada número en [1, 2, 3] y almacena el nuevo array en result (debería ser [2, 4, 6]).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Use .filter to keep only the numbers greater than 4 from [3, 7, 2, 9, 1], in a variable big (it should be [7, 9]). · Usa .filter para mantener solo los números mayores que 4 de [3, 7, 2, 9, 1], en una variable big (debería ser [7, 9]).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Use .forEach to add every number in [4, 8, 15] to · hasta total (it should end up 27). · Usa .forEach para sumar cada número en [4, 8, 15] a total (debería terminar siendo 27).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.