[javascript] Remove empty strings from array while keeping record Without Loop?

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.

This question is related to javascript arrays indexing string removeall

The answer is


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


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

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

as returned v is implicity converted to truthy


var newArray = oldArray.filter(function(v){return v!==''});

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

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to indexing

numpy array TypeError: only integer scalar arrays can be converted to a scalar index How to print a specific row of a pandas DataFrame? What does 'index 0 is out of bounds for axis 0 with size 0' mean? How does String.Index work in Swift Pandas KeyError: value not in index Update row values where certain condition is met in pandas Pandas split DataFrame by column value Rebuild all indexes in a Database How are iloc and loc different? pandas loc vs. iloc vs. at vs. iat?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to removeall

Remove empty strings from array while keeping record Without Loop?