DEV Community

Cristian Fernando
Cristian Fernando

Posted on • Edited on

Paracetamol.js💊| #216: Explica este código JavaScript

Explica este código JavaScript

Dificultad: Intermedio

const numbers = [1, 2 ,3, 4, 5];
const fn = (arr) => {
  return arr.flatMap((number) =>[ [number - 1] ])
}
console.log(fn(numbers)) // 🤔
Enter fullscreen mode Exit fullscreen mode
  • A. [ [ [0], [1], [2], [3], [4] ] ]
  • B. [1, 2, 3, 4, 5]
  • C. [0, 1, 2, 3, 4]
  • D. [ [0], [1], [2], [3], [4] ]

Respuesta en el primer comentario.

Top comments (1)

Collapse
 
duxtech profile image
Cristian Fernando

Respuesta:

  • D. [ [0], [1], [2], [3], [4] ]

flatMap() es un método de los arreglos super interesante, fusiona 2 métodos: map() y flat(), y los implementa como si fuera solo 1.

En palabras sencillas lo que hace flatMap() es iterar item por item sobre el arreglo en el cual se implementa (como si fuera un map()) y posteriormente "aplana" dicho item (como si fuera un flat()).

En el ejemplo, cada a cada iteración del item le restamos 1 y luego aplanamos en un nivel el resultado de dicha iteración, no olvidemos que tanto map() como flatMap() regresa un nuevo arreglo, por ende cada item será regresado en un arreglo independiente que finalmente esta anidado en el nuevo arreglo que devuelve flatMap() y por ello el resultado es [ [0], [1], [2], [3], [4] ].

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay