Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!