1
var arr = [ 4, "Pete", "test", 8, "John", "", "test" ];

How can i remove from this array values test and empty string? How is the best method for this?

Tom Mesgert
  • 1,271
  • 2
  • 10
  • 6

4 Answers4

6
var arr = [ 4, "Pete", "test", 8, "John", "", "test" ]; 
var l = arr.length;

while( l-- ) {
    if( arr[l] === "test" || arr[l] === "" ) {
        arr.splice(l, 1);
    }
}

//> arr
//[4, "Pete", 8, "John"]
Esailija
  • 130,716
  • 22
  • 250
  • 308
  • `arr.splice( arr.indexOf('test'), 1 );` – jAndy Aug 07 '12 at 11:43
  • @jAndy not really, there are multiple items to be removed. And using indexOf multiple times here would be cringeworthy because of the `n²`-ess – Esailija Aug 07 '12 at 11:44
  • oh yea you're right. didn't realize there are multiple values. My solution was flawed anyhow because of `-1` false positives on no-match – jAndy Aug 07 '12 at 11:45
2

Alternative: filter

var arr = [ 4, "Pete", "test", 8, "John", "", "test" ]
           .filter(function(v){return String(v).length && v !== 'test';});
//=> arr = [4, "Pete", 8, "John"];
KooiInc
  • 104,388
  • 28
  • 131
  • 164
  • `Array.prototype.filter` works non-destructive, you need to assign the value back to `arr`. Beside that, why not just calling `return v !== 'test';` ? – jAndy Aug 07 '12 at 11:48
1

check it may help you if you want to remove single Item

http://jsfiddle.net/HWKQY/

Rnk Jangir
  • 661
  • 6
  • 23
0

if you know the index of your item in array you can easily use splice like

arr.splice(index,howmany)

howmany=The number of items to be removed

http://www.w3schools.com/jsref/jsref_splice.asp

rahul
  • 7,048
  • 5
  • 33
  • 46