Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

190
Vistas
javascript map function returned undefined
const numbers = [1, 2, 3, 4];
const filteredNumbers = numbers.map((num, index) => {
  if (index < 3) {
    return num;
  }
});

// filteredNumbers is [1, 2, 3, undefined]

According to my understanding callback function should return all numbers of array if their index is less than 3 so it should return 1,2,3 and stop after that and number 4 can not be returned as if condition says index should be less than 3. I am wondering why it returned undefined for index 3 number.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

.map is an isomorphism and preserves the length of the given array.

So if the callback function does not return anything, the index will be undefined.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You want to user a filter function instead if you need to filter array elements that meet a certain condition.

const numbers = [1, 2, 3, 4];
const filteredNumbers = numbers.filter((_, index) => index < 3);

console.log(filteredNumbers);

about 4 years ago · Juan Pablo Isaza Denunciar

0

If you want just to get the first 3 items in the array, I recommend using slice.

const numbers = [1, 2, 3, 4];
console.log(numbers.slice(0, 3));

Second solution is use filter instead of map.

const numbers = [1, 2, 3, 4];
const filteredNumbers = numbers.filter((num, index) => {
  return index < 3
});

console.log(filteredNumbers)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda