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

70
Visualizações
Prevent arrray.map returning undefined when condition/callback is not met

I was writing some code and something puzzled me. I have an array of numbers called alarmsList. Now I wish to iterate through this list and if a value is higher than 60 for example I want to create a new object array (collection) where we store the high value and it's index from the original array. So take the following code

const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];

const highAlarmsList = alarmsList.map((item, index) => {
    if(item > 60) {
        return ({ value: item, index })
    }
});

console.log(highAlarmsList)

The console.log outputs the following

[
    undefined,
    {
        "value": 61,
        "index": 1
    },
    {
        "value": 77,
        "index": 2
    },
    undefined,
    undefined,
    undefined,
    undefined,
    undefined,
    {
        "value": 85,
        "index": 8
    },
    undefined,
    undefined,
    undefined
]

This output is what I require but how do I prevent the undefined values being returned? I thought about using array.filter but that doesn't seem appropriate? Should I use a different array method? I don't want to use a for loop and push to a new array unless that is the best/only way to achieve the new array without the undefined values being returned.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use Array.filter() to removing the undefined values by using Boolean as the predicate:

const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];

const highAlarmsList = alarmsList.map((item, index) => {
  if(item > 60) {
    return ({ value: item, index })
  }
}).filter(Boolean);

console.log(highAlarmsList)

You can use Array.flatMap() and return empty arrays instead of undefined, but that might effect performance for huge arrays:

const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];

const highAlarmsList = alarmsList.flatMap((item, index) => 
  item > 60 ? { value: item, index } : []
);

console.log(highAlarmsList)

about 4 years ago · Juan Pablo Isaza Relatório

0

map creates a new array by running the callback on every element of the array. If the condition does not satisfy it will return undefined or null. So it not possible to skip the element from the output.

Alternatively you can ue reduce or filter

const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];

const highAlarmsList = alarmsList.reduce((acc, item, index) => {
  item > 60 && acc.push({
    value: item,
    index
  })
  return acc;
}, [])

console.log(highAlarmsList)

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