Deleting falsy values from an array

Viewed 546

I'm studying at freeCodeCamp, and currently learning basic algorithms. I'm doing the falsy bouncer exercise at which you need to remove all falsy values from the array. Sadly there was only the advanced answer for the task, that uses the filter() method. I've decided to make a basic one, but currently stuck.

function bouncer(arr) { 

//*loops through array*    

for (let i = 0; i < arr.length; i++) {  

// *if there is a value that is falsy, delete that value from the array*    

if (arr[i] == 0 || arr[i] == NaN || arr[i] == null || arr[i] == false || arr[i] == "" || arr[i] == undefined) {        

delete arr[i];

     }    

   }    

return arr;

} 

console.log(bouncer([7, "ate", "", false, 9]));

It returns:

7,ate,,,9.

The function, indeed removed the falsy values, but I'm left with those three periods(,,,). Is there a way to make this function to work more correct and to return truthy values without those periods, without losing the simplicity of the function? Appreciate your help.

5 Answers

delete only works on objects. filter will do what you want:

const arr = [7, "ate", "", false, 9]

console.log(arr.filter(x => x))

filter retains only those elements in the array for which the function returns true - here I use x => x because you only want truthy elements

This will do

var m = arr.filter(Boolean);

Since you are new to Javascript and you need your code to work other than a different solution, you can do this

remove delete arr[i]; and replace it with arr.splice(i,1); i--;

This will remove the item in ith position and 1 means 1 item from ith position. Since the element in ith position is removed and a new element is in there. We need to continue again from there. So we need to add i--. Otherwise in the next iteration it will start from the next element instead of ith position.

function bouncer(arr) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == 0 || Number.isNaN(arr[i]) || arr[i] == null || arr[i] == false || arr[i] == "" || arr[i] == undefined) {
            arr.splice(i, 1);
            i--;
        }
    }
    return arr;
}

console.log(bouncer([7, NaN, "ate", "", false, 9]));

Delete works only on Object.

Simply you can do it like this since you're wiling to use simple for loop

function bouncer(arr) {
let op =[];
for (let i = 0; i < arr.length; i++) {
  if(arr[i]){
    op.push(arr[i]);
  }
}
return op;
}

console.log(bouncer([7, "ate", "", false, 9]));

Used map method and Boolean() for comparison.

const bouncer = arr => {

    let newArr = [];

    arr.map(e => {
        if (Boolean(e) == true) {
            newArr.push(e)
        }
    });


    return newArr;
}
Related