Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda