1

I'm having a problem removing empty or undefined elements from an array. I tried with this:

function clean(item) {
    for (var i = 0; i < item.length; i++) {
        if (item[i] === undefined || item[i] == "") {
            item.splice(i, 1);
            i--;
        }
    }

    return item;
};

I don't have any result.

This is example of my array:

example of my array

2
  • 1
    Why not use filter? let newArray = someArray.filter(Boolean) will remove all falsy things from someArray. Commented Feb 7, 2018 at 17:51
  • I pasted your function to the developers console, ran clean(["", "One", "Two", "", "Three", "", "Four"]) and got the expected, clean result: ["One", "Two", "Three", "Four"] - maybe you should check if there is something else that's causing you issues. Commented Feb 7, 2018 at 17:53

3 Answers 3

2
arr = arr.filter((entry) => { return entry.trim() != '' })
Sign up to request clarification or add additional context in comments.

Comments

0

Here's a useful snippet I've written in the past.

Array.prototype.empty = function() {
    for (var i = 0, s = this.length; i < s; i++) { this.pop(); }
    return this;
};

Array.prototype.removeAll = function(item) {
    var result = [];

    for (var i = 0, j = 0, s = this.length; i < s; i++) {
        if (this[i] != item) { result[j++] = this[i]; }
    }

    this.empty();
    for (var i = 0, s = result.length; i < s;) { this.push(result[i++]); }
};

Sure it may not be the best solution in the world, but it works, plus with this function you can always use it to remove other chars/specific elements from an array. Personally, I also prefer the syntax of using this, but that's just me, I personally think it's neater to write something like:

arrayVar.removeAll("");

Rather than something more like:

arrayVar = clean(ArrayVar);

All I know is that this solution works.

Comments

0

You can transfer the array to a temp array while not adding the empty or undefined ones

function clean(item) {
    var tempArr = [];
    for (var i = 0; i < item.length; i++) {
        if (item[i] !== undefined && item[i] != "") {
            tempArr.push(item[i]);
        }
    }
    return tempArr;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.