49

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
  • 31,391
  • 7
  • 56
  • 78
Niraj Chauhan
  • 7,677
  • 12
  • 46
  • 78

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
  • 94,763
  • 41
  • 167
  • 253
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
  • 65,616
  • 14
  • 114
  • 135
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
  • 795,719
  • 175
  • 1,089
  • 1,143
Dukeland
  • 146
  • 4