Search code examples
javascriptarrayssplice

javascript array clean function


Simple function to clean an array if it has null or empty values, so if we have:

[ 'click1', 'click2', null, '', '', 'submitForm' ]

...it will return:

[ 'click1', 'click2', 'submitForm' ]

Here is my code:

function squeakyClean(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] == null || arr[i] == '') {
      arr.splice(i);
    };
  };
  return arr;
}

I have a for loop to check each value in the array and an if statement to see if it is equal to null or and empty string, if so I used array splice method to remove the value and then return the clean array outside the for loop.

It works if you enter an array with no empty strings or null values, but if I enter [ 1, , 2, 3, 0, -1, 1.1 ] it returns [1] which it should not do. What am I missing here?

PS: I have looked how other people solved this using without a for loop and splice method, but I am interested in how to solve it using these two.


Solution

  • Your code is fine apart from your use of the .splice method where you must also specify the number of items on from this index to delete.

    Example: Array.splice(index, numberOfItemsFromIndex);

    Therefore to fix your code it should be as simple as:

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

    (Splice Documentation)