46

Possible Duplicate:
Remove specific element from a javascript array?

I am having an array, from which I want to remove a value.

Consider this as an array

[ 'utils': [ 'util1', 'util2' ] ]

Now I just want to remove util2. How can I do that, I tried using delete but it didn't work.

Can anyone help me?

cнŝdk
  • 30,215
  • 7
  • 54
  • 72
Niraj Chauhan
  • 7,274
  • 11
  • 44
  • 77

3 Answers3

13

Use the splice method:

var object = { 'utils': [ 'util1', 'util2' ] }

object.utils.splice(1, 1);

If you don't know the actual position of the array element, you'd need to iterate over the array and splice the element from there. Try the following method:

for (var i = object.utils.length; i--;) {
    var index = object.utils.indexOf('util2');

    if (index === -1) break;

    if (i === index) {
        object.utils.splice(i, 1); break;
    }
}

Update: techfoobar's answer seems to be more idiomatic than mine. Consider using his instead.

David G
  • 90,891
  • 40
  • 158
  • 247
5

You can use Array.splice() in combo with Array.indexOf() to get the desired behavior without having to loop through the array:

var toDelete = object.utils.indexOf('util1');
if(toDelete != -1) {
    object.utils.splice(toDelete, 1);
}
techfoobar
  • 63,712
  • 13
  • 108
  • 129
0

I think there is no such thing called associative array in Javascript. It is actually an object.

[ 'utils': [ 'util1', 'util2' ] ]

For this line, I don't think it would compile. You should write this instead.

var obj = { 'utils': [ 'util1', 'util2' ] }

So to remove the element "util2" in the array (the inside array), there are 2 ways.

  1. use pop()

    obj["utils"].pop(); // obj["utils"] is used to access the "property" of the object, not an element in associative array
    
  2. reduce the length

    obj["utils"].length --;
    
Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
Dukeland
  • 146
  • 4