Remove empty elements from an array in Javascript

How do I remove empty elements from an array in JavaScript?

Is there a straightforward way, or do I need to loop through it and remove them manually?


I use this method, extending the native Array prototype:

Array.prototype.clean = function(deleteValue) {
  for (var i = 0; i < 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 you 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 i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

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

Simple ways:

var arr = [1,2,,3,,3,null,,0,,undefined,4,,4,,5,,6,,,,];

// (filter - JS 1.6 and above)
arr = arr.filter(function(n){ return n != undefined }); 

arr // [1, 2, 3, 3, 0, 4, 4, 5, 6]

//or - (only for arrays items which are numbers is numbers' strings)**
arr = arr.filter(Number) // [1, 3, 3, 4, 4, 5, 6]

// ES6 style (Firefox FTW)
arr.filter(n => true) // [1, 2, 3, 3, null, 0, undefined, 4, 4, 5, 6]

// or if "null" values are to be removed:
arr.filter(n => n)

or - (only for single array items of type "text")

['','1','2',3,,'4',,undefined,,,'5'].join('').split(''); 
// output:  ["1","2","3","4","5"]

or - Classic way: simple iteration

var arr = [1,2,null, undefined,3,,3,,,0,,,[],,{},,5,,6,,,,],
    len = arr.length, i;

for(i = 0; i < len; i++ )
    arr[i] && arr.push(arr[i]);  // copy non-empty values to the end of the array

arr.splice(0 , len);  // cut the array and leave only the non-empty values

arr // [1,2,3,3,[],Object{},5,6]


via jQuery:

var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];

arr = $.grep(arr,function(n){ return n == 0 || n });

arr // [1, 2, 3, 3, 0, 4, 4, 5, 6]


UPDATE - just another fast, cool way (using ES6):

var arr = [1,2,null, undefined,3,,3,,,0,,,4,,4,,5,,6,,,,], 
    temp = [];

for(let i of arr)
    i && temp.push(i); // copy each non-empty value to the 'temp' array

arr = temp;
delete temp; // discard the variable

arr // [1, 2, 3, 3, 4, 4, 5, 6]

Remove empty values

['foo', '',, ' ', true, [], [1], {}, undefined].filter(String)

// ["foo", " ", true, [1], Object {}, undefined]

Remove falsely values

Another method that removes the "falsey" values of empty string "" , 0 and undefined

[1, 2,, 3,, 3,undefined,,"",false,null,0,NaN, 4," ", 4,true, 5,, 6,,,,].filter(Boolean);

// [1, 2, 3, 3, 4, " ", 4, true, 5, 6]

If you 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(/(rn|n|r)/gm,"")});

Example:

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

Return:

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

UPDATE (based on Alnitak's comment)

In some situations you 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 });

Return:

["hello", 0, 1, 100, " "]
链接地址: http://www.djcxy.com/p/982.html

上一篇: 为什么在PHP中===比==快?

下一篇: 在Javascript中删除数组中的空元素