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

175
Vistas
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 Respuestas
Responde la pregunta

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 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