If I have a javascript array of numbers
[1, 2, 5, 7, 5, 4, 7, 9, 2, 4, 1]
And I want to search through that array and remove a particular number like 4 giving me
[1, 2, 5, 7, 5, 7, 9, 2, 1]
What's the best way to do that
I was thinking it might look like
for(var i = 0; i < myarray.length; i++) {
if(myarray[i] == 4) {
myarray.remove(i)
}
}
But there is no remove
function for an array. Also if I remove an element from the array it messes up my i
unless I correct it.
You can use .splice()
to remove one or more items from an array and if you iterate from back to front of the array, your indexing doesn't get messed up when you remove an item.
var arr = [1, 2, 5, 7, 5, 4, 7, 9, 2, 4, 1];
for (var i = arr.length - 1; i >= 0; i--) {
if (arr[i] == 4) {
arr.splice(i, 1);
}
}
personally, i like to use a re-usable function with the filter method:
//generic filter:
function without(a){return this!=a;}
//your data:
var r= [1, 2, 5, 7, 5, 4, 7, 9, 2, 4, 1];
//your data filtered against 4:
var no4=r.filter(without, 4);
//verify no 4s:
alert(no4); //shows: "1,2,5,7,5,7,9,2,1"
if you want this to mutate the original array, you can just wipe and push the new values into old array:
function without(a){return this!=a;}
var r= [1, 2, 5, 7, 5, 4, 7, 9, 2, 4, 1], //orig
r2=r.slice(); //copy
r.length=0; //wipe orig
[].push.apply( r, r2.filter(without, 4)); //populate orig with filtered copy
r; // == [1, 2, 5, 7, 5, 7, 9, 2, 1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With