[Solved-7 Solutions] Remove empty elements from an array in javascript - javascript tutorial



Problem:

How to remove empty elements from an array in JavaScript ?

Solution 1:

Removing all the empty elements like null,0,'',"",undefined using function

function arr_filter(arr) {
    var ind = -1,arr_len = arr ? arr.length : 0,resInd = -1,res = [];

    while (++ind < arr_len) {
        var val = arr[ind];

        if (val) {
            res[++resInd] = val;
        }
    }

    return res;
}

Solution 2:

We use this method, extending the native Array prototype:

Array.prototype.clean = function(deleteValue) {
  for (var we = 0; we < this.length; i++) {
    if (this[i] == deleteValue) {         
      this.splice(i, 1);
      i--;
    }
  }
  return this;
};

test = new Array("", "One", "Two", "", "Three", "", "Four").clean("");
test2 = [1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,];
test2.clean(undefined);

Or we can simply push the existing elements into other array:

// Will remove all falsy values: undefined, null, 0, false, NaN and "" (empty string)
function cleanArray(actual) {
  var newArray = new Array();
  for (var we = 0; we < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

cleanArray([1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,]);

Solution 3:

If we need to remove ALL empty values ("", null, undefined and 0):

arr = arr.filter(function(e){return e}); 

To remove empty values and Line breaks:

arr = arr.filter(function(e){ return e.replace(/(\r\n|\n|\r)/gm,"")});

Example:

arr = ["hello",0,"",null,undefined,1,100," "]  
arr.filter(function(e){return e});

Output

["hello", 1, 100, " "]

Solution 4:

In some situations we may want to keep "0" in the array and remove anything else (null, undefined and ""), this is one way:

arr.filter(function(e){ return e === 0 || e });

Output

["hello", 0, 1, 100, " "]

Solution 5:

Here we can do this,

[1, false, "", undefined, 2].filter(Boolean); // [1, 2]

or using underscorejs.org :

_.filter([1, false, "", undefined, 2], Boolean); // [1, 2]
// or even:
_.compact([1, false, "", undefined, 2]); // [1, 2]

If you've got Javascript 1.6 or later we can use Array.filter using a trivial return true callback function, e.g.:

arr = arr.filter(function() { return true; });
  • Since .filter automatically skips missing elements in the original array.
  • The MDN page linked above also contains a nice error-checking version of filter that can be used in JavaScript interpreters that don't support the official version.
  • Note that this will not remove null entries nor entries with an explicit undefined value, but the OP specifically requested "missing" entries.

Solution 7:

The clean way to do it.

var arr = [0,1,2,"Thomas","false",false,true,null,3,4,undefined,5,"end"];
arr = arr.filter(Boolean);
// [1, 2, "Thomas", "false", true, 3, 4, 5, "end"]


Related Searches to javascript tutorial - Remove empty elements from an array in javascript