0

Why am i getting such output?[solved]

Lately, i was playing around with array methods and i got this while filtering an array. In the conditions, if i should uncomment the else statement the entire array elements would be returned instead of the values i provided for the else condition. Why is it so? https://code.sololearn.com/W3PcFHZDot1S/?ref=app

27th Aug 2020, 12:39 PM
Infinite
Infinite - avatar
4 Answers
+ 1
In filter, it should return either true or false.. Something returning text equlent in boolean is true.. So "not found" also text to be true for all values.. Without else it just returning matched values as true.. You shloud return none or false from else.. This is may you looking for.. "use strict" let arr = ["we","me","us","they"]; let h = prompt("search") function find(a){ return a.filter(b=>{ if(h==b){ return b; } else { return false; } }) } console.log(find(arr)=="" ? "not found" : find(arr));
27th Aug 2020, 1:27 PM
Jayakrishna 🇼🇳
+ 2
This would be a cleaner way to write it: function find(a){ return a.filter(b=>{ return h===b; }); } What you return in the filter function is interpreted as either true or false. Returning a string like "we" or "me" is a little confusing but those values can be interpreted as true. Either an element from the array is filtered or it is not. The decision is black and white.
27th Aug 2020, 1:34 PM
Josh Greig
Josh Greig - avatar
+ 1
You're welcome.. Infinite
27th Aug 2020, 1:39 PM
Jayakrishna 🇼🇳
0
Jayakrishna🇼🇳 thanks, i really appreciate
27th Aug 2020, 1:35 PM
Infinite
Infinite - avatar