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?

Thanks

share|improve this question

feedback

15 Answers

up vote 58 down vote accepted

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:

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,,,,]);
share|improve this answer
1  
Could clone it and return that instead... – neonski Nov 11 '08 at 16:31
12  
WARNING: The 2nd option will remove any elements from an array considered "falsy," i.e. the values of false, 0, null & undefined. This array would end up with nothing at all in it: [null,,,0,,0,0,0,false,null,0] even though I might want the elements with values of 0, as in this array: [1,0,1,0,0,1] – Jason Bunting Nov 11 '08 at 16:48
Yes the second method, but the first one you pass the value of the elements that you want to delete [null,,,0,,0,0,0,false,null,0].clean(null) == [0,0,0,0,false,0] – CMS Nov 11 '08 at 16:49
2  
I realize that - which is why I only spoke of the second option. As for the first one, it is so narrow in scope that I would hesitate to make it part of the Array's prototype. See Alnitak's answer on this page for something that would be more ideal. Yours does allow for chaining though, obviously. – Jason Bunting Nov 11 '08 at 17:02
Your first solution is really nice if you don't have access to the "filter" method. Else I believe Alnitak's answer is better. – Joe Pineda Nov 11 '08 at 18:06
show 2 more comments
feedback

I needed to do this same task and came upon this thread. I ended up using the array "join" to create a string using a "_" separator, then doing a bit of regex to:-

1. replace "__" or more with just one "_",
2. replace preceding "_" with nothing "" and similarly 
3. replace and ending "_" with nothing ""

...then using array "split" to make a cleaned-up array:-

var myArr = new Array("","","a","b","","c","","","","","","","","","e","");
var myStr = "";

myStr = myArr.join("_");

myStr = myStr.replace(new RegExp(/__*/g),"_");
myStr = myStr.replace(new RegExp(/^_/i),"");
myStr = myStr.replace(new RegExp(/_$/i),"");
myArr = myStr.split("_");

alert("myArr=" + myArr.join(","));

...or in 1 line of code:-

var myArr = new Array("","","a","b","","c","","","","","","","","","e","");

myArr = myArr.join("_").replace(new RegExp(/__*/g),"_").replace(new RegExp(/^_/i),"").replace(new RegExp(/_$/i),"").split("_");

alert("myArr=" + myArr.join(","));

...or, extending the Array object :-

Array.prototype.clean = function() {
  return this.join("_").replace(new RegExp(/__*/g),"_").replace(new RegExp(/^_/i),"").replace(new RegExp(/_$/i),"").split("_");
};

var myArr = new Array("","","a","b","","c","","","","","","","","","e","");

alert("myArr=" + myArr.clean().join(","));
share|improve this answer
feedback
array=array.fitler(/\w/);
filter + regexp
share|improve this answer
feedback

If using a library is an option I know underscore.js has a function called compact() http://documentcloud.github.com/underscore/ it also has several other useful functions related to arrays and collections.

Here is an excerpt from their documentation:

_.compact(array)

Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", undefined and NaN are all falsy.

_.compact([0, 1, false, 2, '', 3]);

=> [1, 2, 3]

share|improve this answer
feedback

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

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

Example:

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

Return:

["hello", 1, 100, " "]
share|improve this answer
+1 I like this trick. – pimvdb Oct 28 '11 at 8:59
Great trick! Works like a charm, thanks. – Bery Apr 3 at 10:29
feedback

Pure javascript:

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

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

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

or

arr = arr.filter(Number)


via jQuery:

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

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

arr // [1, 2, 3, 3, 4, 4, 5, 6]
share|improve this answer
5  
note - filter was introduced in javascript 1.6 – vsync May 16 '10 at 12:52
thanks, very elegant! – Alex Ivasyuv Feb 10 '11 at 15:43
The other answers didn't work for me becuase i had an array of arrays. This works great though +1. – Timothy Ruhle Feb 16 '11 at 1:06
very nice, swiftly pinched and added to my code :) – sapatos Oct 30 '11 at 8:28
4  
earliest IE support for filter is IE9 standards mode. – yincrash Nov 2 '11 at 2:19
feedback

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"]
share|improve this answer
2  
Empty elements are undefined; this basically removes all falsy values. – pimvdb Mar 26 '11 at 17:17
feedback

What about that:

js> [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,].filter(String).join(',')
1,2,3,3,0,4,4,5,6
share|improve this answer
1  
join() === join(',') :) – pimvdb Mar 26 '11 at 17:17
feedback

@Alnitak

Actually Array.filter works on all browsers if you add some extra code. See below.

var array = ["","one",0,"",null,0,1,2,4,"two"];

function isempty(x){
if(x!=="")
    return true;
}
var res = array.filter(isempty);
document.writeln(res.toJSONString());
// gives: ["one",0,null,0,1,2,4,"two"]

This is the code you need to add for IE, but filter and Functional programmingis worth is imo.

//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }

    return res;
  };
}
share|improve this answer
yes, that's exactly what I said in my answer. – Alnitak Apr 28 '10 at 19:08
feedback

This works, I tested it in AppJet (you can copy-paste the code on its IDE and press "reload" to see it work, don't need to create an account)

/* appjet:version 0.1 */
function Joes_remove(someArray) {
    var newArray = [];
    var element;
    for( element in someArray){
        if(someArray[element]!=undefined ) {
            newArray.push(someArray[element]);
        }
    }
    return newArray;
}

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

print("Original array:", myArray2);
print("Clenased array:", Joes_remove(myArray2) );
/*
Returns: [1,2,3,3,0,4,4,5,6]
*/
share|improve this answer
feedback

If you've got Javascript 1.6 or later you can use Array.filter using a function similar to the isNullOrUndefined function in Jason's answer. See:

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter

This page also contains a nice error-checking version of filter that can be used in JavaScript interpreters that don't support the official version.

share|improve this answer
You're right! It can be so simple as this (and works!): test3 = [1,2,,3,,3,,,,7,,,7,,,0,,,4,,4,,5,,6,,undefined,,null,,]; printp( "Using array's native filtering: ", test3.filter( function(value){return (value==undefined) ? 0 : 1;} ) ); – Joe Pineda Nov 11 '08 at 18:02
Yeah, it works - but not all browsers have JavaScript 1.6, so it's only that good. – Jason Bunting Nov 11 '08 at 22:23
+1 As Alnitak said, they have the code that can be used in the case of not having js 1.6 available – Sameer Alibhai Apr 28 '10 at 18:50
feedback

You may find it easier to loop over your array and build a new array out of the items you want to keep from the array than by trying to loop and splice as has been suggested, since modifying the length of the array while it is being looped over can introduce problems.

You could do something like this:

function removeFalsyElementsFromArray(someArray) {
    var newArray = [];
    for(var index = 0; index < someArray.length; index++) {
        if(someArray[index]) {
            newArray.push(someArray[index]);
        }
    }
    return newArray;
}

Actually here is a more generic solution:

function removeElementsFromArray(someArray, filter) {
    var newArray = [];
    for(var index = 0; index < someArray.length; index++) {
        if(filter(someArray[index]) == false) {
            newArray.push(someArray[index]);
        }
    }
    return newArray;
}

// then provide one or more filter functions that will 
// filter out the elements based on some condition:
function isNullOrUndefined(item) {
    return (item == null || typeof(item) == "undefined");
}

// then call the function like this:
var myArray = [1,2,,3,,3,,,,,,4,,4,,5,,6,,,,];
var results = removeElementsFromArray(myArray, isNullOrUndefined);

// results == [1,2,3,3,4,4,5,6]

You get the idea - you could then have other types of filter functions. Probably more than you need, but I was feeling generous... ;)

share|improve this answer
feedback

Try this. Pass it your array and it will return with empty elements removed. *Updated to address the bug pointed out by Jason

function removeEmptyElem(ary) {
    for (var i=ary.length;i>=0;i--) {
        if (ary[i] == undefined)  {
            ary.splice(i, 1);
        }   	
    }
    return ary;
}
share|improve this answer
2  
DON'T use this function, it fails for obvious reasons: Try it on this array: var myArray = [1,2,,3,,3,,,,,,4,,4,,5,,6,,,,]; – Jason Bunting Nov 11 '08 at 16:03
Oh yes it is somewhat buggy. If you fix it I will accept your answer. – DrJokepu Nov 11 '08 at 16:04
This has been updated and should no longer experience the same error – Matty Nov 11 '08 at 16:15
The iteration start with i=ary.length which is wrong. It should be i=ary.length-1 – GetFree Jun 5 '09 at 13:45
Its still buggy. it starts with length and checks for array[i] which will be always undefined in first case. – Mutant Nov 8 '11 at 22:15
feedback

You'll have to loop and then splice()

share|improve this answer
This is not optimal at all and also it might happen that you break something with splice inside loops. Not recommended option at all. – Tom Roggero Dec 23 '11 at 3:28
feedback

You'll need use some form of iteration to accomplish this. There isn't any built in mechanism in JavaScript to accomplish the task.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.