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

178
Visualizações
javascript map and filter related issue

I know how filter and map works but was stuck up in a particular scenario

I see that filter returns 0 if no match is found but is there a way to pass on that to map in case there is no match. eg

    const tasks = [
  {
    'name'     : 'Write for Envato Tuts+',
    'duration' : 120
  },
  {
    'name'     : 'Work out',
    'duration' : 60
  },
  {
    'name'     : 'Procrastinate on Duolingo',
    'duration' : 240
  }
];
let difficult_tasks1=tasks.filter(x=>x.duration>=200).map(x=>x? console.log(x):alert("error")); 
console.log(difficult_tasks1.length)

above prints as expected i.e first console prints the object x and 2nd prints the length 1

my issue is to get an alert of error when there is no match

let difficult_tasks1=tasks.filter(x=>x.duration>=400).map(x=>x? console.log(x):alert("error")); 

above prints nothing but i was expecting an alert of error.

let difficult_tasks1=tasks.filter(x=>x.duration>=400).map(x=>console.log("a"+x));

even above doesnt even prints anything..doesnt get to console part in the map

What i want is if nothing is filtered, i still want to return something or show an error

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

0

You can check if your filter passes data using .length property of array

let difficult_tasks1=tasks.filter(x=>x.duration>=200).map(x=>x? console.log(x):alert("error")); 

const filtered = tasks.filter(x => x.duration >= 200)
if (filtered.length > 0) {
   filtered.map((x) => {
      console.log(x)
      return x;
   });
} else {
   alert('Error');
}
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