By Tamas Czinege


2008-11-11 15:48:54 8 Comments

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?

30 comments

@vsync 2010-05-16 12:02:48

Simple ways:

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


arr.filter(n => n)
// [1, 2, 3, -3, 4, 4, 5, 6]

arr.filter(Number) 
// [1, 2, 3, -3, 4, 4, 5, 6]

arr.filter(Boolean) 
// [1, 2, 3, -3, 4, 4, 5, 6]

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;

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

Remove empty values

['foo', '',,,'',,null, ' ', 3, true, [], [1], {}, undefined, ()=>{}].filter(String)

// ["foo", null, " ", 3, true, [1], Object {}, undefined, ()=>{}]

@vsync 2010-05-16 12:52:48

note - filter was introduced in javascript 1.6

@Timothy Ruhle 2011-02-16 01:06:06

The other answers didn't work for me becuase i had an array of arrays. This works great though +1.

@sapatos 2011-10-30 08:28:29

very nice, swiftly pinched and added to my code :)

@yincrash 2011-11-02 02:19:21

earliest IE support for filter is IE9 standards mode.

@ilumin 2013-01-12 08:38:21

for pure javascript it should be arr = arr.filter(function(n){return n; });

@vsync 2013-01-12 20:04:50

@yincrash - as I wrote in my first comment

@broofa 2013-02-16 18:32:20

Given answer doesn't work. You need to return the element, as noted by @ilumin. E.g. [1,null,undefined,3,].filter(function(){;return true}) => [1, null, undefined, 3]

@vsync 2013-02-17 00:11:12

@broofa - it does work. just tried it on IE, FF and CHROME. from W3C: filter calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a true value.. and 'undefined' is not an empty value by the way, so as null.

@broofa 2013-02-18 14:20:22

@vsync - This is a matter of semantics, where it depends on what is meant by "empty". It obviously should include cases where (key in array) == false, which is what your solution filters on. But I'm pretty confident that most people would also expect this to include the case where (key in array) && (array[key] === undefined) as well, which your solution doesn't handle.

@vsync 2013-02-18 15:04:00

@broofa - well, you are right and you are wrong, because I answered the OP's question in the exact manner he needed, but it is true that if you want to detect 'undefined' (which is NOT considered an empty value) than you need to change the filter function

@Atav32 2013-07-26 16:32:34

foo.join("").split("") only seems to work if the strings are single characters

@John Kurlak 2014-03-07 21:55:44

Your pure JavaScript code has a bug. If the array has a value with "0" in it, the value will be filtered out because "0" is falsy. What you want is: arr.filter(function (n) { return (n !== undefined && n !== null); });

@vsync 2014-03-08 09:29:05

@JohnKurlak - you're right, I fixed it, but not like you've said.

@Augustin Riedinger 2014-05-03 10:56:28

jQuery should have a built in method for that. Or even ES6!

@Sheepy 2015-02-09 04:32:47

ES6 can do it even simpler arr.filter(e=>e) and this can be chained by map, reduce, etc.

@vsync 2015-02-09 10:40:28

@Sheepy - cool, but it would take forever for ES6 to become a standard

@Sheepy 2015-02-09 10:44:39

@vsync Forever may come faster than you think, because the browsers have agreed to push questionable stuffs to ES7. IE technical preview have most ES6, and production Firefox can already fun this code.

@vsync 2015-02-09 10:50:24

yeah, that's what they said about ES5, I remember that day. and still, hardly anyone is using ES5...by the time ES7 will come, humans will be living on mars

@sahbeewah 2015-04-07 03:39:29

@vsync, as @JohnKurlak mentioned, arr = arr.filter(Number) is still wrong and you should remove it from the answer

@Semicolon 2015-08-25 02:07:58

As several people pointed out, arr.filter(n => n) and its es5 equivalent will remove falsy values, which may not be desired. However filter, like other array methods, only iterates over defined values anyway. Thus filter(n => true) is a nice clean way to condense a sparse array.

@clever_bassi 2015-10-16 00:17:15

This should be the accepted answer. Neat solution. Thanks.

@Alnitak 2015-11-23 11:59:23

@ayushi it shouldn't - it confuses the original question by mostly removing falsey entries rather than missing entries.

@vsync 2015-11-23 15:53:21

@Alnitak - I confused nothing, I simply extended the original question because it is more likely that people who come here from Google will be interested in both removing empty items as well as providing them the solutions of removing other kind of items which might be considered "empty" to them, in some situations.

@Foo 2015-12-11 07:50:35

$.grep(arr,function(n){ return n == 0 || n }); will keep value 0 in the array :)

@vsync 2016-10-26 15:50:49

@DavChana - Your comment is irrelevant to this discussion. you can use the above answer's code however you wish, you are free to modify it if you prefer !== instead of !=...

@cnexans 2017-08-29 13:02:28

Better typeof n !== 'undefined' instead of n != undefined

@vsync 2017-09-01 13:48:56

@cnexans - Do you have a scenario which can back the claim?

@cnexans 2017-09-03 00:05:29

n != undefined may have two problems: 1. With variables that are not yet defined, it will throw an error 2. Undefined can be redeclared (not in the global scope) i.e. function example() { var undefined = 1; }. Using typeof n != 'undefined' is a way to always prevent these (horrible but possible) cases.

@vsync 2017-09-03 11:36:44

@cnexans - Thank you but respectfully disagree. Those are ridicules edge-cases that I've never ever encountered in all my years of coding in javascript. Have you? If you get so deep into thinking about any absurd edge case there will be no end. this is why developers obey the rules and do not create variables named undefined. else, the code will punish them with bugs, which they well deserve for.

@Ramakay 2017-12-24 18:33:47

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

@Jonathan Arbely 2018-01-15 11:55:09

Regarding $.grep, is there a way to log/capture all removed values and their IDs in the faulty/unmodified array? I think this information can be useful to sync with other arrays that may be related to the one cleaned from empty and false values.

@Jamie Ridding 2019-07-11 22:56:19

delete temp; - This has no effect in JavaScript, as it can only be performed against object properties - attempting to access temp after this line will result in the same output as if you hadn't done delete temp; in the first place.

@Andrea Perdicchia 2019-07-04 10:36:28

this is my solution for clean empty fields.

Start from fees object: get only avail attribute (with map) filter empty fields (with filter) parse results to integer (with map)

fees.map( ( e ) => e.avail ).filter( v => v!== '').map( i => parseInt( i ) );

@Kanan Farzali 2018-07-10 11:27:25

ES6: let newArr = arr.filter(e => e);

@CMS 2008-11-11 16:12:59

EDIT: This question was answered almost 9 year ago, when there were not much useful built-in methods in the Array.prototype.

Now, certainly I would just recommend you to use the filter method.

Take in mind that this method will return you a new array with the elements that pass the criteria of the callback function you provide to it, for example, if you want to remove null or undefined values:

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

var filtered = array.filter(function (el) {
  return el != null;
});

console.log(filtered);

It will depend on what you consider to be "empty", for example if you were dealing with strings, the above function wouldn't remove elements that are an empty string.

One common pattern that I see often used is to remove elements that are falsy, which include an empty string "", 0, NaN, null, undefined, and false.

You can simply pass to the filter method, the Boolean constructor function, or simply return the same element in the filter criteria function, for example:

var filtered = array.filter(Boolean);

Or

var filtered = array.filter(function(el) { return el; });

In both ways this works because the filter method in the first case, calls the Boolean constructor as a function, converting the value, and in the second case, the filter method internally converts the return value of the callback implicitly to Boolean.

If you are working with sparse arrays, and you are trying to get rid of the "holes", you can simply use the filter method passing a callback that returns true, for example:

var sparseArray = [0, , , 1, , , , , 2, , , , 3],
    cleanArray = sparseArray.filter(function () { return true });

console.log(cleanArray); // [ 0, 1, 2, 3 ]

Old answer: Don't do this!

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,,,,]);

@neonski 2008-11-11 16:31:19

Could clone it and return that instead...

@Jason Bunting 2008-11-11 16:48:42

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]

@CMS 2008-11-11 16:49:56

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]

@Jason Bunting 2008-11-11 17:02:10

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.

@Joe Pineda 2008-11-11 18:06:32

Your first solution is really nice if you don't have access to the "filter" method. Else I believe Alnitak's answer is better.

@AlfaTeK 2010-02-22 11:24:27

And what has the best performance? 1) or 2) approach? (or something like jQuery.grep() / Array.filter )

@Alnitak 2011-05-10 19:35:09

@AlfaTek - on all apart from the newest browsers #2 will have the best performance, because arrays in JS aren't really arrays. The splice call is really expensive on older browsers because they have to renumber all of the array keys to close up the gap.

@karlipoppins 2013-04-04 10:32:25

i love how so many of those best answers are native extensions while so many people preach how evil it is

@Jorre 2013-05-11 12:33:43

Also, you could write your loop a bit more performant by avoiding counting array elements on every loop like so: for(var i = 0, j = actual.length; i<j; i++)

@mila 2014-11-26 09:14:23

@neonski your suggestion didn't work for me. I tried results['data'] = results['data'].slice(0); and results['data'] still contains null values

@Alnitak 2015-02-24 17:15:24

I can't believe how many votes this and the 2nd answer are getting. Neither actually answer the question that was asked.

@David 2015-07-04 08:24:37

WARNING: the first method could make for (i in array) to fail. To prevent it you should place a if (array.hasOwnProperty(i)) { inside the loop.

@Alnitak 2015-11-23 11:57:30

@David no, in modern code you should safely extend Array.prototype using Object.defineProperty to make the new function a non-enumerable property and then avoid the performance hit caused by putting .hasOwnProperty in every loop.

@Dude 2018-08-14 11:13:45

downvote because its outdated. you can do this with a oneliner nowadays. const filteredArray = unfilteredArray.filter(item => *condition to keep item in array*)

@creep3007 2018-08-15 06:51:18

Another short and beautiful way using ECMA 5 could be [1, 2,,, 3,,,,,,,,, 4,, 4,,, 5,,, 6,,,,,].filter( e => e !== ('' || null || undefined))

@Miquel 2018-10-10 16:10:39

Nowadays this shouldn't be the accepted answer

@CMS 2018-10-10 18:13:50

@Miquel, you're right, I have updated the answer, it has been almost 10 years!

@Wel 2019-06-30 17:06:39

array [,'d','x'] with return el != null return ,d,x while if I used return el I get the correct result d,x why is that ??

@AmerllicA 2018-10-16 06:15:51

Just ES6 and newer versions method, assume array is below:

 const arr = [1,2,3,undefined,4,5,6,undefined,7,8,undefined,undefined,0,9];

Simple way:

 const clearArray = arr.filter( i => i );

@stalinrajindian 2018-10-11 06:43:51

Another one way:

function filter_array(test_array) {
    var index = -1,
        arr_length = test_array ? test_array.length : 0,
        resIndex = -1,
        result = [];

    while (++index < arr_length) {
        var value = test_array[index];

        if (value) {
            result[++resIndex] = value;
        }
    }

    return result;
}
console.log(filter_array([NaN, 0, 15, false, -22, '',undefined, 47, null]));

@tsh 2018-01-09 07:28:03

For removing holes, you should use

arr.filter(() => true)
arr.flat(0) // Currently stage 3, check compatibility before using this

For removing hole, and, falsy (null, undefined, 0, -0, NaN, "", false, document.all) values:

arr.filter(x => x)

For removing hole, null, and, undefined:

arr.filter(x => x != null)

arr = [, null, (void 0), 0, -0, NaN, false, '', 42];
console.log(arr.filter(() => true)); // [null, (void 0), 0, -0, NaN, false, '', 42]
console.log(arr.filter(x => x)); // [42]
console.log(arr.filter(x => x != null)); // [0, -0, NaN, false, "", 42]

@samayo 2018-01-09 14:43:17

This should be high up in the answer. Can you expand what you mean by holes/hole ..?

@Jimmy Obonyo Abor 2018-04-23 20:06:09

@samayo holes are unfilled array items ie [, ,]

@KuanYu Chu 2019-04-21 11:30:30

By using arr.filter(x => x), JS will check whether x is truthy or falsy, i.e. if (x), therefore only the truthy value will be assigned to the new list.

@lepe 2011-10-28 01:41:09

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(/(\r\n|\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, " "]

@Vladimirs 2013-03-29 15:51:13

Yup this is nice cuz removes "" as well.

@Koen. 2014-11-02 00:45:05

The test function could be a little more explicit: function(e){return !!e}

@Sheepy 2015-02-09 04:35:51

@Koen Please note that !!e will include NaN (unlike 0) whereous e would not (like 0).

@Alnitak 2015-02-24 17:16:18

Doesn't actually answer the question that was asked.

@lepe 2015-02-25 00:51:46

@Alnitak: it all depends on how you define "empty". I updated my answer based in your comment. Thanks!

@John Bower 2016-02-02 22:04:36

Nice and elegant. +1

@Mark Schultheiss 2016-04-17 13:53:40

OR use var myarr=[1, 2,, 3,, 3,undefined,,"",,0, 4,, 4,, 5,, 6,,,,].filter(Boolean); removes undefined,"" and 0

@Jitendra virani 2018-02-21 06:58:16

var data= { 
    myAction: function(array){
        return array.filter(function(el){
           return (el !== (undefined || null || ''));
        }).join(" ");
    }
}; 
var string = data.myAction(["I", "am","", "working", "", "on","", "nodejs", "" ]);
console.log(string);

Output:

I am working on nodejs

It will remove empty element from array and display other element.

@Jitendra virani 2018-02-21 09:35:15

output: 'I am working on nodejs'. it will remove empty element from array and display other element.

@GGO 2018-02-21 09:45:54

I improved your answer. Please try to make simple, clear and readable answer ;)

@siddhant narang 2016-07-13 18:46:42

How about doing it this way

// Removes all falsy values 
arr = arr.filter(function(array_val) { // creates an anonymous filter func
    var x = Boolean(array_val); // checks if val is null
    return x == true; // returns val to array if not null
  });

@DavChana 2016-10-26 14:53:03

Please explain this a bit to help the other users.

@Gapur Kassym 2017-12-28 10:44:03

You should use filter to get array without empty elements. Example on ES6

const array = [1, 32, 2, undefined, 3];
const newArray = array.filter(arr => arr);

@KARTHIKEYAN.A 2017-11-29 12:46:19

use filter to remove empty string in array.

var s = [ '1,201,karthikeyan,K201,HELPER,[email protected],8248606269,7/14/2017,45680,TN-KAR24,8,800,1000,200,300,Karthikeyan,11/24/2017,Karthikeyan,11/24/2017,AVAILABLE\r',
  '' ]
var newArr = s.filter(function(entry) { return entry.trim() != ''; })

console.log(newArr); 

@Sandeep M 2017-03-30 05:33:59

This might help you : https://lodash.com/docs/4.17.4#remove

var details = [
            {
                reference: 'ref-1',
                description: 'desc-1',
                price: 1
            }, {
                reference: '',
                description: '',
                price: ''
            }, {
                reference: 'ref-2',
                description: 'desc-2',
                price: 200
            }, {
                reference: 'ref-3',
                description: 'desc-3',
                price: 3
            }, {
                reference: '',
                description: '',
                price: ''
            }
        ];

        scope.removeEmptyDetails(details);
        expect(details.length).toEqual(3);

scope.removeEmptyDetails = function(details){
            _.remove(details, function(detail){
                return (_.isEmpty(detail.reference) && _.isEmpty(detail.description) && _.isEmpty(detail.price));
            });
        };

@KARTHIKEYAN.A 2017-03-29 10:28:02

var data = [null, 1,2,3];
var r = data.filter(function(i){ return i != null; })

console.log(r) 

[1,2,3]

@Martin Andersson 2017-05-11 08:22:39

This is the obviously correct way to do it and should be at the top!

@ML13 2017-03-22 20:24:54

Simple ES6

['a','b','',,,'w','b'].filter(v => v);

@Trevor 2017-01-02 16:48:18

This one will only remove empty values and not falsey ones, which I think is more desirable.

There is an option to also remove null values.

This method should be much faster than using splice.

    function cleanArray(a, removeNull) {
        var i, l, temp = [];
        l = a.length;
        if (removeNull) {
            for (i = 0; i < l; i++) {
                if (a[i] !== undefined && a[i] !== null) {
                    temp.push(a[i]);
                }
            }
        } else {
            for (i = 0; i < l; i++) {
                if (a[i] !== undefined) {
                    temp.push(a[i]);
                }
            }
        }
        a.length = 0;
        l = temp.length;
        for (i = 0; i < l; i++) {
            a[i] = temp[i];
        }
        temp.length = 0;
        return a;
    }
    var myArray = [1, 2, , 3, , 3, , , 0, , null, false, , NaN, '', 4, , 4, , 5, , 6, , , , ];
    cleanArray(myArray);
    myArray;

@Puni 2016-11-24 10:30:54

If anyone is looking for cleaning the whole Array or Object this might help.

var qwerty = {
    test1: null,
    test2: 'somestring',
    test3: 3,
    test4: {},
    test5: {
        foo: "bar"
    },
    test6: "",
    test7: undefined,
    test8: " ",
    test9: true,
    test10: [],
    test11: ["77","88"],
    test12: {
        foo: "foo",
        bar: {
            foo: "q",
            bar: {
                foo:4,
                bar:{}
            }
        },
        bob: {}
    }
}

var asdfg = [,,"", " ", "yyyy", 78, null, undefined,true, {}, {x:6}, [], [2,3,5]];

function clean_data(obj) {
    for (var key in obj) {
        // Delete null, undefined, "", " "
        if (obj[key] === null || obj[key] === undefined || obj[key] === "" || obj[key] === " ") {
            delete obj[key];
        }
        // Delete empty object
        // Note : typeof Array is also object
        if (typeof obj[key] === 'object' && Object.keys(obj[key]).length <= 0) {
            delete obj[key];
        }
        // If non empty object call function again
        if(typeof obj[key] === 'object'){
            clean_data(obj[key]);
        }
    }
    return obj;
}

var objData = clean_data(qwerty);
console.log(objData);
var arrayData = clean_data(asdfg);
console.log(arrayData);

Output:

Removes anything that is null, undefined, "", " ", empty object or empty array

jsfiddle here

@Matty 2008-11-11 15:58:17

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 - 1; i >= 0; i--) {
        if (ary[i] == undefined)  {
            ary.splice(i, 1);
        }       
    }
    return ary;
}

@Jason Bunting 2008-11-11 16:03:21

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,,,,];

@Tamas Czinege 2008-11-11 16:04:53

Oh yes it is somewhat buggy. If you fix it I will accept your answer.

@Matty 2008-11-11 16:15:58

This has been updated and should no longer experience the same error

@GetFree 2009-06-05 13:45:14

The iteration start with i=ary.length which is wrong. It should be i=ary.length-1

@Mutant 2011-11-08 22:15:51

Its still buggy. it starts with length and checks for array[i] which will be always undefined in first case.

@michael.zech 2016-03-14 12:56:17

'Misusing' the for ... in (object-member) loop. => Only truthy values appear in the body of the loop.

// --- Example ----------
var field = [];

field[0] = 'One';
field[1] = 1;
field[3] = true;
field[5] = 43.68;
field[7] = 'theLastElement';
// --- Example ----------

var originalLength;

// Store the length of the array.
originalLength = field.length;

for (var i in field) {
  // Attach the truthy values upon the end of the array. 
  field.push(field[i]);
}

// Delete the original range within the array so that
// only the new elements are preserved.
field.splice(0, originalLength);

@Alnitak 2018-01-15 10:45:47

the code is right, the comment is wrong. The act of using for ... in is what removes the undefined keys from the array, but you've actually no code here to otherwise accept only "truthy" values

@John Slegers 2016-03-11 18:26:51

The best way to remove empty elements, is to use Array.prototype.filter(), as already mentioned in other answers.

Unfortunately, Array.prototype.filter() is not supported by IE<9. If you still need to support IE8 or an even older version of IE, you could use the following polyfill to add support for Array.prototype.filter() in these browsers :

if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun/*, thisArg*/) {
    'use strict';
    if (this === void 0 || this === null) {
      throw new TypeError();
    }
    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== 'function') {
      throw new TypeError();
    }
    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++) {
      if (i in t) {
        var val = t[i];
        if (fun.call(thisArg, val, i, t)) {
          res.push(val);
        }
      }
    }
    return res;
  };
}

@VIJAY P 2015-12-11 11:31:28

What about this(ES6) : To remove Falsy value from an array.

var arr = [0,1,2,"test","false",false,true,null,3,4,undefined,5,"end"];

arr.filter((v) => (!!(v)==true));

//output:

//[1, 2, "test", "false", true, 3, 4, 5, "end"]

@rpearce 2015-10-12 20:52:21

Here is an example using variadic behavior & ES2015 fat arrow expression:

Array.prototype.clean = function() {
  var args = [].slice.call(arguments);
  return this.filter(item => args.indexOf(item) === -1);
};

// Usage
var arr = ["", undefined, 3, "yes", undefined, undefined, ""];
arr.clean(undefined); // ["", 3, "yes", ""];
arr.clean(undefined, ""); // [3, "yes"];

@sqram 2014-07-10 07:51:28

foo = [0, 1, 2, "", , false, 3, "four", null]

foo.filter(function(e) {
    return e === 0 ? '0' : e
})

returns

[0, 1, 2, 3, "four"]

@c4urself 2012-11-30 18:25:11

With Underscore/Lodash:

General use case:

_.without(array, emptyVal, otherEmptyVal);
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);

With empties:

_.without(['foo', 'bar', '', 'baz', '', '', 'foobar'], '');
--> ["foo", "bar", "baz", "foobar"]

See lodash documentation for without.

@jamesconant 2015-07-14 19:44:42

You actually probably want to use #compact

@Samuel Brandão 2016-03-18 09:44:07

Issue with #compact is that it removes any falsy values. So if your array contain 0 values, they will also be removed.

@Bogdan Gersak 2014-10-27 14:21:37

This is another way to do it:

var arr = ["a", "b", undefined, undefined, "e", undefined, "g", undefined, "i", "", "k"]
var cleanArr = arr.join('.').split(/\.+/);

@Tim Baas 2015-05-19 07:25:08

This is a really bad idea.. What if one of the values is "a.string.with.dots"? It would be broken into pieces when creating the new array...

@Bogdan Gersak 2015-05-19 17:42:30

It's up to you what character you choose for join/split, you don't need to use a dot if you have a.string.with.dots

@Synoli 2015-12-18 17:42:35

@BogdanGersak What if you cannot guarantee at design time whether the string is going to contain, or not contain, any specific character?

@Josh Bedo 2014-11-08 18:10:58

Since nobody else mentioned it and most people have underscore included in their project you can also use _.without(array, *values);.

_.without(["text", "string", null, null, null, "text"], null)
// => ["text", "string", "text"]

@John Miller 2014-10-21 22:23:15

When using the highest voted answer above, first example, i was getting individual characters for string lengths greater than 1. Below is my solution for that problem.

var stringObject = ["", "some string yay", "", "", "Other string yay"];
stringObject = stringObject.filter(function(n){ return n.length > 0});

Instead of not returning if undefined, we return if length is greater than 0. Hope that helps somebody out there.

Returns

["some string yay", "Other string yay"]

@aamarks 2018-04-24 15:45:58

+1 as this is very practical and exactly what I usually need working with string arrays, but be aware that this removes numbers (if they aren't in string form) since they don't have a .lenghth so, ["", "some string yay", "", "", 123, "Other string yay"].filter(function(n){ return n.length > 0}) //gives your same result removing 123 Replacing that function... with String, ironically, leaves numbers in but would give the same result in your given array.

@Alnitak 2008-11-11 16:29:34

If you've got Javascript 1.6 or later you 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.

@Joe Pineda 2008-11-11 18:02:55

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;} ) );

@Jason Bunting 2008-11-11 22:23:02

Yeah, it works - but not all browsers have JavaScript 1.6, so it's only that good.

@Sameer 2010-04-28 18:50:01

+1 As Alnitak said, they have the code that can be used in the case of not having js 1.6 available

@Ash Blue 2014-07-03 11:29:09

Not working for me on the latest version of Chrome

@sqram 2014-07-10 07:45:52

Yes, won't work. Seems that as long as it's not undefined, it's true.

@Alnitak 2014-07-10 07:56:35

@katsh I've clarified - the code above does work to remove entries for which no value exists at all, which (I've subsequently) learnt is semantically different to the case of a key that exists but which has undefined as its given value.

@Hafthor 2015-10-15 19:06:53

Array.filter is ES5 and works on IE9 and up.

@Alan CN 2016-10-06 21:13:03

To remove undefined or null entries, just make a small modification... arr = arr.filter(function(v) { return v; });

@Alnitak 2016-10-07 09:28:07

@AlanCN you've completely missed my point. The OP asked to remove missing entries, whilst the bulk of the answers here (incorrectly) remove any "falsey" entries.

@AmerllicA 2018-01-14 10:02:46

Awesome, it is work properly.

@lcabral 2010-02-25 11:56:57

Filtering out invalid entries with a regular expression

array = array.filter(/\w/);
filter + regexp

@FreeLightman 2016-08-01 15:33:21

Does this work? it shows an error TypeError: [object RegExp] is not a function

@andlrc 2012-12-10 09:25:25

Simply one liner:

[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]

@Andrew 2013-02-03 00:50:38

This is really cool - I have a newb question though: it looks like you're using a class name as a function call -- is that typecasting? I haven't seen this before and am not sure I get why passing Boolean works as a function...

@andlrc 2013-02-07 16:38:07

If you treat Boolean as a function it will simply return true or false wether the value is truly/falsy.

@ELLIOTTCABLE 2015-02-24 17:28:21

You're not treating Boolean as a function; it is a function. (A completely normal function, except that it's natively-implemented.) Somebody needs to do a little research on the JavaScript object model. ;)

@andlrc 2015-02-24 17:33:26

@ELLIOTTCABLE Im just gonna leave this here, (true).constructor === Boolean. And then tell me if we can do this with other build-ins in JS. ;)) (of course excluted the other 5 build-in constructors. (String, Array, Object, Function, Number))

@ELLIOTTCABLE 2015-03-10 09:47:28

No idea what you're saying, @null.

@Alnitak 2015-11-23 11:55:42

@dev-null all JS constructors are functions - what matters is whether they also permit themselves to be called without new or not. Boolean does, as do the other standard types, but typically a browser's DOM functions do not.

@Sai Ram 2017-01-31 06:13:05

Will fail both if there is value 0 in the array

Related Questions

Sponsored Content

37 Answered Questions

[SOLVED] Deleting an element from an array in PHP

  • 2008-12-15 20:28:55
  • Ben
  • 2343455 View
  • 2297 Score
  • 37 Answer
  • Tags:   php arrays unset

37 Answered Questions

[SOLVED] How do I loop through or enumerate a JavaScript object?

55 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5891856 View
  • 7345 Score
  • 79 Answer
  • Tags:   javascript arrays

38 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

41 Answered Questions

[SOLVED] Sort array of objects by string property value

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

12 Answered Questions

[SOLVED] How can I add new array elements at the beginning of an array in Javascript?

  • 2011-11-10 00:35:22
  • Moon
  • 711476 View
  • 1417 Score
  • 12 Answer
  • Tags:   javascript arrays

18 Answered Questions

[SOLVED] How do I empty an array in JavaScript?

  • 2009-08-05 09:08:39
  • akano1
  • 2309759 View
  • 2199 Score
  • 18 Answer
  • Tags:   javascript arrays

Sponsored Content