6

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.

8
  • do you wish to do it in-place or to generate a new array ? Commented Sep 4, 2013 at 18:54
  • possible duplicate of Remove specific element from an array? Commented Sep 4, 2013 at 18:55
  • 1
    ... or delete myarray[i] - and don't forget to skip the increment on iterations in which you delete! Commented Sep 4, 2013 at 18:55
  • @LightStyle oh that looks interesting. Vincent Piel I don't fully understand the difference. Commented Sep 4, 2013 at 18:55
  • 2
    just counting down is much easier than skipping increments Commented Sep 4, 2013 at 18:57

5 Answers 5

8

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

Comments

6

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]

1 Comment

this is a great solution - your formatting is making me anxious though 😅
2

I prefer do something like this:

removeEmail(event){
   myarray.splice(myarray.indexOf(event.target.id), 1)
}

myaraay.splice() Going to remove, myarray.indexOf() gives the number or whatever you wan to remove from inside the array. Thats the simplest way without need a loop over. :)

Comments

1

John Resig, creator of jQuery created a very handy Array.remove method that I always use it in my projects.

// Array Remove - By John Resig (MIT Licensed)
    Array.prototype.remove = function(from, to) {
      var rest = this.slice((to || from) + 1 || this.length);
      this.length = from < 0 ? this.length + from : from;
      return this.push.apply(this, rest);
    };

So, you can use your code like this:

// Remove the second item from the array
myarray.remove(1);
// Remove the second-to-last item from the array
myarray.remove(-2);
// Remove the second and third items from the array
myarray.remove(1,2);
// Remove the last and second-to-last items from the array
myarray.remove(-2,-1);

---Edit----

for(var i = 0; i < myarray.length; i++) {
    if(myarray[i] == 4) {
        myarray.remove(i);
    }
}

Use your code like this to remove specific value.

3 Comments

OP is looking to remove elements with a specific value
The code you added at the end in your edit won't work because when you remove an item, the array indexes change and you will skip evaluating some items.
So you can use splice()! The name of this function, the parameter names and the results aren't obvious. My recommendation is to just use splice(index,length)
1

Here is a remove function based on index

function  remove(array, index){
     for (var i = index; i < arr.length-1; i++) {
          array[i] = array[i+1];    
      }
}

Basically, what this does is shifts all the elements from the index to the "left." Not quite sure how splice works, but i'm guessing it works exactly the same way.

After adding that function to your code all you have to do is.

for(var i = 0; i < myarray.length; i++) {
    if(myarray[i] == 4) {
       remove(myarray,i);
    }
}

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.