Remove different items from JS array

I’m trying to solve an exercise where I need to create the function cleanArray and remove various items from an array. This is as far as I could get

function cleanArray(arr) {

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

        if (arr[i] === null || 0 || "" || false || undefined) {
            arr.splice(i, 1);

            return arr
        }
    }
}

But this only filters out null for me. I’ve tried putting the items to remove in a separate array or going one by one, but then it either returns undefined or only filters out the 0 even when it’s not the first item to remove.

I’ve seen other answers where people use filter or indexOf but I want to see if there’s a way to do it with splice. Is it not possible to use the logical operators here?

2 thoughts on “Remove different items from JS array”

  1. This is not the way you make multiple comparisons. Your if condition can be written as:

    arr[i] === null || 0 === 1 || "" === 1 || false === 1 || undefined === 1
    

    Now it is clear why it doesn’t work, right? You need to compare arr[i] to every one of these values:

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

    Note: this approach probably won’t work. Since you are removing elements from your array (and hence it is getting shorter and shorter), once an element is removed, you will be in the wrong index, and by the time you reach the end of your loop, you will encounter undefined index errors. Finally, move your return statement out of the loop.

    I suggest
    If you want to stay away from Array.filter(), I suggest creating a new array and only pushing in the values you want:

    function cleanArray(arr) {
      var newArr = [];
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] === null || arr[i] === 0 || arr[i] === "" || arr[i] === false || arr[i] === undefined) {
          continue;
        } else {
          newArr.push(arr[i]);
        }
      }
      return newArr;
    }
    
    Reply
  2. You could simplify this doing two simple steps.

    1. Create a function to verify if a primitive value is falsy
    2. Using a filter or reducer to isolate those values from the source array

    Example:

    const array = [1,2,"", null, undefined, 3, "4", true, 5, false, "6"]
    
    const isFalsy = value => !!value === false
    
    // this one is just to make the code more readable
    const isTrully = value => !isFalsy(value)
    
    const trullyValues = array.reduce((a, c) => isFalsy(c) ? a : [...a, c], [])
    
    // will return the same from above
    const filteredyTrullyValues = array.filter(isTrully)
    
    Reply

Leave a Comment