16

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 am lost as to how and do this correctly in JS.

The following will not work because of above reason:

for (var i=0, l=src.length; i<l; i++) {

    if (src[i].match(/^[\s\t]{2,}$/) !== null) src.splice(i, 1);

}

Error:

Uncaught TypeError: Cannot call method 'match' of undefined

canon
  • 40,609
  • 10
  • 73
  • 97
tenub
  • 3,386
  • 1
  • 16
  • 25
  • Do you actually want to change the array in place or are you alright with generating a second, filtered array? – canon Dec 18 '13 at 21:36

9 Answers9

31

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.

Paul Draper
  • 78,542
  • 46
  • 206
  • 285
  • He has `l=src.length` in the initialization section of the `for` loop, not the test section. – Barmar Dec 18 '13 at 21:42
  • [Array.splice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) _doesn't_ modify an array in-place? Explain, please. – canon Dec 18 '13 at 21:43
  • running on 4.5 hours of sleep led me to miss the simple issue that i was trying to cache the array length when i actually shouldn't have been. >_< the question now is which method achieves the same goal quickest or with the least amount of effort? – tenub Dec 18 '13 at 21:48
  • @tenub, that answer will depend on how often whitespace elements appear in practice. (e.g. lots, almost never, etc.). The more whitespace elements, the faster `filter` is than `splice`. If there are almost never whitespace elements, `splice` is faster. – Paul Draper Dec 18 '13 at 21:53
  • @tenub, caching the length wasn't the only issue. When you remove an item from an array it shifts the remaining items down an index... so, you'll skip the one that was shifted down into the current index, `i`. – canon Dec 30 '13 at 14:07
  • I've modified the code to the following, filtering undefined values etc out: ````return !!str && /\S/.test(str);```` – timbru31 Sep 24 '15 at 18:28
5

Another filter based variation - reusable (function)

    function removeWhiteSpaceFromArray(array){
    return array.filter((item) => item != ' ');
}
liron_hazan
  • 1,396
  • 2
  • 19
  • 27
4

const words = ['spray', 'limit', 'elite', 'exuberant', ' ', ''];

const result = words.filter(word => word.trim().length > 0);

console.log(result);
Surojit Paul
  • 1,232
  • 9
  • 11
3

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().

Gosha
  • 51
  • 4
2

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);
Jed Fox
  • 2,979
  • 5
  • 28
  • 38
canon
  • 40,609
  • 10
  • 73
  • 97
0

And for a new generation (namely ES2015):

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

More on trim()

Adrian Lynch
  • 8,237
  • 2
  • 32
  • 40
0

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!!

Antolin Bernas
  • 182
  • 3
  • 9
0

Here's another approach.

var data = JSON.parse(arrayval.split(/\s/).join(''));
tripleee
  • 175,061
  • 34
  • 275
  • 318
0
function clearSpace(arr){
    for (var key in arr) {
        if (arr[key] == "") {
            arr.splice(key, 1)
            clearSpace(arr)
        }
    }
}
var arr = ["","a","b","",""]
clearSpace(arr)

//I hope this helps you!!
//Vu Tien Luong - 3GTEL
  • Please don't post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes – Ran Marciano Dec 09 '20 at 06:28