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

talemyn
  • 7,822
  • 4
  • 31
  • 52
mrkibzk
  • 227
  • 4
  • 17
  • 1
    Why not use filter? `let newArray = someArray.filter(Boolean)` will remove all falsy things from `someArray`. – CRice Feb 07 '18 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. – bonidjukic Feb 07 '18 at 17:53

3 Answers3

2
arr = arr.filter((entry) => { return entry.trim() != '' })
Akash Dathan
  • 4,348
  • 2
  • 24
  • 45
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.

JO3-W3B-D3V
  • 2,124
  • 11
  • 30
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;
}
simple-thomas
  • 671
  • 7
  • 20