Chris Martinez Chris Martinez - 4 months ago 8
Javascript Question

Removing an element from a javascript array causing issues

So I'm a little stuck as to why this isn't working. I'm trying to remove all of the empty strings in an array and it keeps giving me back an array that is just one empty string. Any ideas?

function splitNames(){
var names = document.getElementById("1").value.split("\n");
for(var i = 0; i<=names.length; i++){
if(names[i]==""){
names = names.splice(i, 1);
console.log(names);
}
}
console.log(names);
}


The string would look like this by the way.

Hi

Hello

(remove this one)

Bonjour

blah

(remove this one)

(remove this one)

blah

The array comes out to this ["Hi", "Hello","",...]

Answer

Perhaps the simplest way to do this is to use the filter function and search for truthy values. By default, empty strings are false.

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

var strings = ["zebras", "trees", "forests", "", "hi", "wizards", "", "", "lizards"];

strings = strings.filter((e) => e);

console.log(strings);

It's important to note that empty strings by default are false. However, strings that contain only whitespace characters are true. In that scenario, my example would not work and you would have to do this

strings.filter((e) => e.trim());

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Comments