Remove Whitespace-only Array Elements

Viewed 48333

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

9 Answers

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

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

console.log(result);

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

Here's another approach.

var data = JSON.parse(arrayval.split(/\s/).join(''));
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
Related