98

This question was asked here: Remove empty strings from array while keeping record of indexes with non empty strings

If you'd notice the given as @Baz layed it out;

"I", "am", "", "still", "here", "", "man"

"and from this I wish to produce the following two arrays:"

"I", "am", "still", "here", "man"

All the Answers to this question referred to a form of looping.

My question: Is there a possibility to remove all indexes with empty string without any looping? ... is there any other alternative apart from iterating the array?

May be some regex or some jQuery that we are not aware of?

All answers or suggestions are highly appreciated.

Community
  • 1
  • 1
Universal Grasp
  • 1,835
  • 3
  • 20
  • 29

7 Answers7

341
var arr = ["I", "am", "", "still", "here", "", "man"]
// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(Boolean)
// arr = ["I", "am", "still", "here", "man"]

filter documentation


// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(v=>v!='');
// arr = ["I", "am", "still", "here", "man"]

Arrow functions documentation

Isaac
  • 11,409
  • 5
  • 33
  • 45
  • 3
    I know exactly how you feel, I used it months ago, fixes so many small issues – Isaac Nov 10 '13 at 10:51
  • 14
    @DiegoPlentz people who're still running IE8 are gonna have a lot more problems than just removing blanks in an array... I barely ever consider supporting that browser these days – Isaac Mar 02 '15 at 04:59
  • This is the closest to `array.filter(!!)` that we can currently get :) – james_womack Oct 13 '15 at 21:43
  • 2
    All credit for this answer should go to http://stackoverflow.com/questions/16701319/javascript-regex-split-reject-null – Isaac Jan 11 '16 at 21:31
  • 1
    Some explanation regarding `Boolean` would be nice. – robsch Nov 13 '18 at 13:03
  • @robsch The Boolean function is used as the test function, which converts values to booleans. Empty strings are considered falsy, while non-empty strings are truthy. – psychoslave Jun 22 '23 at 09:27
19
var newArray = oldArray.filter(function(v){return v!==''});
Haitham Ahmed
  • 187
  • 1
  • 8
  • Easily the best answer. Does exactly what the question asks. Doesn't remove zero values. – Bryan Mar 03 '15 at 22:56
10

PLEASE NOTE: The documentation says:

filter is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of filter in ECMA-262 implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming that fn.call evaluates to the original value of Function.prototype.call, and that Array.prototype.push has its original value.

So, to avoid some heartache, you may have to add this code to your script At the beginning.

if (!Array.prototype.filter) {
  Array.prototype.filter = function (fn, context) {
    var i,
        value,
        result = [],
        length;
        if (!this || typeof fn !== 'function' || (fn instanceof RegExp)) {
          throw new TypeError();
        }
        length = this.length;
        for (i = 0; i < length; i++) {
          if (this.hasOwnProperty(i)) {
            value = this[i];
            if (fn.call(context, value, i, this)) {
              result.push(value);
            }
          }
        }
    return result;
  };
}
ErickBest
  • 4,586
  • 5
  • 31
  • 43
4
arr = arr.filter(v => v);

as returned v is implicity converted to truthy

haind
  • 1,000
  • 2
  • 16
  • 28
2

If are using jQuery, grep may be useful:


var arr = [ a, b, c, , e, f, , g, h ];

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

arr is now [ a, b, c, d, e, f, g];

Isaac
  • 11,409
  • 5
  • 33
  • 45
sansid1983
  • 239
  • 1
  • 4
  • 14
1

You can use lodash's method, it works for string, number and boolean type

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

https://lodash.com/docs/4.17.15#compact

Esin ÖNER
  • 1,046
  • 11
  • 9
0

i.e we need to take multiple email addresses separated by comma, spaces or newline as below.

    var emails = EmailText.replace(","," ").replace("\n"," ").replace(" ","").split(" ");
    for(var i in emails)
        emails[i] = emails[i].replace(/(\r\n|\n|\r)/gm,"");

    emails.filter(Boolean);
    console.log(emails);
Atif Hussain
  • 880
  • 12
  • 19
  • `.replace(" ","").split(" ")` "replace all spaces with nothing, then try split at every space" – Isaac Nov 29 '16 at 22:16