0

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","",...]

1
  • You can just use ary.filter(function( item ) {return !!item;}) to remove all empty strings from an array. And you get that error sinceyou replace names with the spliced version every time, makign the array shorter. Either cache the length or use a second array. Commented Jul 6, 2016 at 15:12

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks!! That worked! Can you explain how this works? What exactly is a filter?
A filter, as the name suggests filters a group of elements (an array) based on a condition. Let's say for example you had a list of ingredients and wanted to filter for fruits. You would have an original item list of pasta, bread, pineapples, mangos, carrots. Filtering it to only get the fruits, you would have pineapples, mangos
Ahh, so in this case, the function boolean will only pass on non-empty strings?
Yup, but be careful, strings that contain one or more whitespace characters such as ` ` are true. In that case, my example would not work
0

function splitNames(){
  // var names = document.getElementById("1").value.split("\n");
  var names = "Hi\nHello\n \nGoodBye".split("\n");
  
  var filteredNames = names.filter(function(item){
    return item.trim() !== "";
  });//filter
  
  return filteredNames;
}//splitNames()

console.log( splitNames() );

Comments

0

Create a new array and push what you need.

function splitNames(){
    var names = document.getElementById("1").value.split("\n");
    var newArr = [];

    for(var i = 0; i<=names.length; i++){
        if(names[i]){
            newArr.push(names[i]);
        }
    }

    return newArr.join('\n');
    //console.log(names);

}

Comments

0

try it:

function splitNames(){

    var names = document.getElementById("1").value.split("\n");
    var newArr = names.filter(function(name){
        return name!=="";
    });

    return newArr;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.