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?

1

4 Answers 4

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"]
Sign up to request clarification or add additional context in comments.

3 Comments

arr.splice( arr.indexOf('test'), 1 );
@jAndy not really, there are multiple items to be removed. And using indexOf multiple times here would be cringeworthy because of the -ess
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
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"];

1 Comment

Array.prototype.filter works non-destructive, you need to assign the value back to arr. Beside that, why not just calling return v !== 'test'; ?
1

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

http://jsfiddle.net/HWKQY/

Comments

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

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.