I tired using map ,passed current element and index, checked whether current element is falsy?
then i tired to remove from the array using splice method.
Your code so far
function bouncer(arr) {
// Don't show a false ID to this bouncer.
let newarr=arr.map((el,i)=>{
if(Boolean(el)===false){
arr.splice(i,1);
}
});
return newarr;
}
console.log(bouncer([7, "ate", "", false, 9]));
// [ undefined, undefined, undefined, undefined, ]
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36.
Mr RandellDawson
1.Why should i not mutate the orignal array on which i am mapping? is it a bad practice?
function bouncer(arr) {
// Don't show a false ID to this bouncer.
let newarr=arr.map((el,i)=>{
if(!Boolean(el)){
arr.splice(i,1);
}
return el;
});
return newarr;
}
let x=bouncer([7, "ate", "", false, 9]);
console.log(x);
console.log(x[4]);
// [ 7, 'ate', '', 9, ]
// undefined
Above function does not evaluate Boolean("")as false why ?? You can confirm this in returned array.
Why the last element of array is undefined ? Since i returned the value.
I tried using live Programming Mode , i was unable to understand why it returned undefined as last element.
If you can help please.
Thanks
Around step 10-11 Boolean("") evalutes to true and it returns as el. Same this does not happen with Boolean(false). ?? Why is this happening i don’t understand
I got that map is running till i=4 , i think it is because i remove the a element from original array now at i=4 nothing exist
I wanted to use map somehow, now after running this piece of code below i am sure that if u don’t return any thing in map by default it will return undefined. I think we cannot skip returning undefined in map.
function bouncer(arr) {
let newarr=arr.map((el,i)=>{
if(Boolean(el)!==false){
return el
}
});
return newarr;
}
console.log(bouncer([7, "ate", "", false, 9]));
//[ 7, 'ate', undefined, undefined, 9 ]
Congrats! I like the arr.filter( falsy=>Boolean(falsy)) answer!
Ya, map was not the best approach here… i mean you could have used it but it’s not really what it is for:
function bouncer(arr) {
// Don't show a false ID to this bouncer.
let temp = []
arr.map( i => {if(Boolean(i)) temp.push(i)})
return temp
}
bouncer([7, "ate", "", false, 9]);
You can kind of hack it together (basically your code using map or forEach) but best to use filter when looking for a true/false thing; such as “Is user online?” … use filter.