Remove Whitespace-only Array Elements

后端 未结 8 879
悲&欢浪女
悲&欢浪女 2020-12-08 17:30

Since using array.splice modifies the array in-place, how can I remove all whitespace-only elements from an array without throwing an error? With PHP we have preg_grep but I

相关标签:
8条回答
  • 2020-12-08 17:51

    Just simply do this example

    // this is you array 
    let array = ["foo","bar","",""]
    
    // remove blanks in array 
    let array_new_value = array.join(" ").trim().split(' ');
    
    // Print to know if really works 
    console.log(array_new_value);
    

    I hope this helps you!!

    0 讨论(0)
  • 2020-12-08 17:52

    Another filter based variation - reusable (function)

        function removeWhiteSpaceFromArray(array){
        return array.filter((item) => item != ' ');
    }
    
    0 讨论(0)
  • 2020-12-08 17:59

    a="remove white spaces"

    a.split(' ').join('').split('');
    

    It returns an array of all characters in {a="remove white spaces"} with no 'space' character.

    You can test the output separately for each method: split() and join().

    0 讨论(0)
  • 2020-12-08 17:59

    And for a new generation (namely ES2015):

    ['1', ' ', 'c'].filter(item => item.trim() !== '')
    

    More on trim()

    0 讨论(0)
  • 2020-12-08 18:01

    A better way to "remove whitespace-only elements from an array".

    var array = ['1', ' ', 'c'];
    
    array = array.filter(function(str) {
        return /\S/.test(str);
    });
    

    Explanation:

    Array.prototype.filter returns a new array, containing only the elements for which the function returns true (or a truthy value).

    /\S/ is a regex that matches a non-whitespace character. /\S/.test(str) returns whether str has a non-whitespace character.

    0 讨论(0)
  • 2020-12-08 18:04

    You removed an item from the array which reduced the array's length. Your loop continued, skipped some indexes (those which were down-shifted into the removed index), and eventually attempted to access an index outside of the new range.

    Try this instead:

    var src = ["1"," ","2","3"];
    var i = src.length;    
    while(i--) !/\S/.test(src[i]) && src.splice(i, 1);
    console.log(src);

    0 讨论(0)
提交回复
热议问题