Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Métodos de Arrays `map`, `filter` | Section
Fundamentos de JavaScript

bookMétodos de Arrays `map`, `filter`

Desliza para mostrar el menú

Arrays often need to be transformed or filtered to create new versions based on existing data. JavaScript provides higher-order array methods like map and filter that make these tasks concise and readable.

These methods help you avoid manual loops and let you focus on what you want to achieve with your data, rather than how to do it step by step. Using higher-order methods leads to code that is easier to maintain, understand, and reuse.

123456
// Using map to create a new array with doubled values const numbers = [1, 2, 3, 4]; const doubled = numbers.map(function(num) { return num * 2; }); console.log(doubled); // [2, 4, 6, 8]
copy

When you use map, JavaScript creates a new array by calling your function once for each element in the original array. The value returned by your function becomes the new value in the resulting array, and the original array is not changed.

123456
// Using filter to create a new array with only even numbers const numbers = [1, 2, 3, 4, 5, 6]; const evens = numbers.filter(function(num) { return num % 2 === 0; }); console.log(evens); // [2, 4, 6]
copy

With filter, your function should return true to keep an element or false to exclude it. Only the elements that pass your test function are included in the new array, while the original array remains unchanged.

Both map and filter loop through the array internally, so you do not need to write a manual loop—they take care of iterating and building the new array for you.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 1. Capítulo 13

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Sección 1. Capítulo 13
some-alt