Possible Duplicate:
Remove item from array by value
I am maintaining string lists like
var keyString = [];
keyString.push("anotherString");
keyString.push("yetAnotherString");
keyString.push("oneLastString");
I want to be able to return all results from keyString
less a value I already know about.
For example, if I have anotherString, then I want to return everything in the array that isn't anotherString.
Obviously this can be done a few ways easily, but I have some restrictions.
I don't want the solution to use any loops, and I don't want to use excessive amounts of memory, and I don't want to modify the original array.
This may be impossible, but I thought I would throw it out there and see if anything exists.
Some possibilities considering your example code, but inside a function (or return
wouldn't make sense). The examples assume you're fine with modifying the original array, since you don't want to copy.
1. Using shift
to remove the first element
function something() {
someObject["keyString"] = [];
someObject["keyString"].push("anotherString");
someObject["keyString"].push("yetAnotherString");
someObject["keyString"].push("oneLastString");
someObject["keyString"].shift();
return someObject;
}
2. Using pop
to remove the last element
function something() {
someObject["keyString"] = [];
someObject["keyString"].push("yetAnotherString");
someObject["keyString"].push("oneLastString");
someObject["keyString"].push("anotherString");
someObject["keyString"].pop();
return someObject;
}
3. Using splice
to remove the middle element
function something() {
someObject["keyString"] = [];
someObject["keyString"].push("yetAnotherString");
someObject["keyString"].push("anotherString");
someObject["keyString"].push("oneLastString");
someObject["keyString"].splice(1,1);
return someObject;
}
You could use filter()
, but this will return a new array as well:
var newArray = keyString.filter( function( el ) {
return el !== 'anotherString';
} );
Not bulletproof but it works:
var a = ["a", "b", "c", "d"];
a.splice( a.indexOf("c"), 1 );
console.log(a); // ["a", "b", "d"];