Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and remove element from array

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.

like image 607
user2748139 Avatar asked Dec 05 '22 09:12

user2748139


2 Answers

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);
    }
}
like image 171
jfriend00 Avatar answered Dec 06 '22 22:12

jfriend00


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]
like image 44
dandavis Avatar answered Dec 06 '22 22:12

dandavis