Remove empty elements from an array in Javascript

2018-12-31 03:20发布

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条回答
泪湿衣
2楼-- · 2018-12-31 03:46

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.

查看更多
忆尘夕之涩
3楼-- · 2018-12-31 03:46

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.

查看更多
流年柔荑漫光年
4楼-- · 2018-12-31 03:49

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"]
查看更多
余生无你
5楼-- · 2018-12-31 03:51

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,,,,]);
查看更多
笑指拈花
6楼-- · 2018-12-31 03:51

Simple ES6

['a','b','',,,'w','b'].filter(v => v);
查看更多
像晚风撩人
7楼-- · 2018-12-31 03:51

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);
查看更多
登录 后发表回答