Last Updated: February 25, 2016
·
27.84K
· artchang

Remove value from array with jQuery

The key tools for removing a value from an array in javascript typically includes finding the index (such as using indexOf), and then using splice() to remove at a specific index.

The problem with indexOf is that it's not supported in Internet Explorer. You'd have to spin your own version of indexOf which is kind of gross.

Instead, there's a cross browser way to do this, and it's pretty damn elegant.

First, check if the value is even in the array with jQuery's utility function, inArray()

value = 1
$.inArray value, array

What inArray() returns is the index of where this value is in the array. So to check if the value is in the array, you just need to make sure it's greater than -1.

value = 1
if $.inArray value, array
    console.log "value is in the array"

As you notice, I'm using coffeescript in these code snippets. So now, you must have realized, "hey, inArray gives you the index already!" So yes, we can just count on jQuery to have safely returned the array to us, and we can use that to splice.

value = 1
index = $.inArray value, array
if index > -1
    array.splice(index, 1)

And that's it, now you can safely remove items from an array in your javascript with jQuery.

If you look at stackoverflow and other resources, they all point to the need of fixing indexOf for IE, but alas, jQuery has done it for us.

  NODES
Community 1
Intern 1
iOS 2
Javascript 11
os 7