简体   繁体   中英

Deleting falsy values from an array

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.

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

这会做

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--; arr.splice(i,1); i--;

This will remove the item in i th position and 1 means 1 item from i th position. Since the element in i th 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 i th 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM