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
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');
}