163

How do I remove the key 'bar' from an array foo so that 'bar' won't show up in

for(key in foo){alert(key);}
Steven Noble
  • 10,204
  • 13
  • 45
  • 57

7 Answers7

283

Don't use delete as it won't remove an element from an array it will only set it as undefined, which will then not be reflected correctly in the length of the array.

If you know the key you should use splice i.e.

myArray.splice(key, 1);

For someone in Steven's position you can try something like this:

for (var key in myArray) {
    if (key == 'bar') {
        myArray.splice(key, 1);
    }
}

or

for (var key in myArray) {
    if (myArray[key] == 'bar') {
        myArray.splice(key, 1);
    }
}
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
going
  • 9,669
  • 4
  • 36
  • 37
  • 3
    +1 Good point, I also like this way: http://ejohn.org/blog/javascript-array-remove/ – Christian C. Salvadó Aug 28 '09 at 05:38
  • 3
    @ThiefMaster - Care to explain? I don't know what that means and keen to learn. As always, an edit is a 1,000,000 times better than an off-hand comment; you should know that with the amount of rep you have. – going Dec 26 '11 at 09:28
  • 22
    Use `for (var key in myArray)` instead of `for (key in myArray)` - otherwise `key` is a global variable and if you call a function inside that loop that has the same problem, you will get unexpected results. – ThiefMaster Dec 26 '11 at 14:16
  • 3
    Note, the second example doesn't work if the array has multiple items in a row that match 'bar'. The index of the array will shift and you will miss splicing half of the items. Instead, use a for loop that decrements the index when a match is found. – Dave Lancea May 06 '14 at 19:24
  • For an array of objects : http://stackoverflow.com/questions/15287865/remove-array-element-based-on-object-property – Fedir RYKHTIK May 12 '14 at 17:30
  • Just a reminder not to try to delete array elements using `splice()` when looking in an array using the array index as the key. Splicing will shorten the array, but the loop may still count up to the previous length of the array. – Quinn Comendant Aug 31 '15 at 21:43
  • Why is this the accepted answer, it only works when the key it's numeric. The accepted answer should be `delete yourArray[key];` and that statement about making it undefined it's false – dnetix Sep 04 '15 at 05:59
  • Given that the OP hasn't shown us how `foo` was created, it could be an array or an object. The best answer I've seen is here: http://stackoverflow.com/questions/8173210/delete-vs-splice-on-associative-array – Paul Masri-Stone Feb 01 '17 at 08:11
  • I like this way: myArray.splice(myArray.indexOf('bar'),1) – stackoverflowsucks Oct 12 '17 at 06:21
  • use `for(var key=myArray.length-1;key>=0;key--)` to avoid problems with index shifting. works with numeric keys only – dw1 Feb 22 '18 at 03:14
65
delete foo[key];

:D

  • 5
    technically that doesn't answer the question. he's looking to remove the key 'bar'. and your key variable doesn't imply that. :P – Kon Oct 16 '08 at 02:45
  • 4
    key='bar'; eval("delete foo."+key); *hides* ;D – olliej Oct 16 '08 at 03:13
  • 3
    Do *NOT* use `eval`. Deleting a key/index of an object/array can be achieved by much simpler methods not using `eval`. – Dinei Sep 03 '15 at 14:40
  • 6
    Actually if you remove from indexed array by delete foo[key] it will stores value in foo[key]=undefined and foo.length will remain same which is wrong. So use SPLICE instead – Павел Иванов Apr 27 '16 at 11:49
  • 1
    use delete foo[key] it wrong; should use foo.splice(key, 1); – vnguyen May 08 '20 at 10:43
42

If you know the key name simply do like this:

delete array['key_name']
Bridge
  • 29,818
  • 9
  • 60
  • 82
user3177525
  • 469
  • 4
  • 2
  • 2
    This is not an array! It's an object (yes, these are called associative arrays in JS, but no, they aren't really, and this method is harmful if you trully work with a JS array). – wintercounter Jul 07 '14 at 15:15
38

An important note: JavaScript Arrays are not associative arrays like those you might be used to from PHP. If your "array key" is a string, you're no longer operating on the contents of an array. Your array is an object, and you're using bracket notation to access the member named <key name>. Thus:

var myArray = [];
myArray["bar"] = true;
myArray["foo"] = true;
alert(myArray.length); // returns 0.

because you have not added elements to the array, you have only modified myArray's bar and foo members.

John Factorial
  • 486
  • 4
  • 7
5

This is how I would do it

 myArray.splice( myArray.indexOf('bar') , 1) 
  • 1
    The Array.prototype.indexOf() method searches for a value within an array, not for a key. So this will not work. – Nadav Jan 23 '18 at 08:02
1

there is an important difference between delete and splice:

ORIGINAL ARRAY:

[<1 empty item>, 'one',<3 empty items>, 'five', <3 empty items>,'nine']

AFTER SPLICE (array.splice(1,1)):

[ <4 empty items>, 'five', <3 empty items>, 'nine' ]

AFTER DELETE (delete array[1]):

[ <5 empty items>, 'five', <3 empty items>, 'nine' ]

AlexeiOst
  • 574
  • 4
  • 13
1

http://www.internetdoc.info/javascript-function/remove-key-from-array.htm

removeKey(arrayName,key);

function removeKey(arrayName,key)
{
 var x;
 var tmpArray = new Array();
 for(x in arrayName)
 {
  if(x!=key) { tmpArray[x] = arrayName[x]; }
 }
 return tmpArray;
}
ling
  • 11
  • 1