8

I have a string indexed array that I would like to remove an item from.

Consider the following example code:

    var arr = new Array();       
    arr[0] = "Zero";
    arr[1] = "One";
    arr[2] = "Two";
    arr.splice(1, 1);

    for (var index in arr)
        document.writeln(arr[index] + " ");

    //This will write: Zero Two

    var arr = new Array();
    arr["Zero"] = "Zero";
    arr["One"] = "One";
    arr["Two"] = "Two";

    arr.splice("One", 1); //This does not work
    arr.splice(1, 1); //Neither does this

    for (var index in arr)
        document.writeln(arr[index] + " ");

    //This will write: Zero One Two

How do I remove "One" from the second example like I did in the first?

scottt
  • 7,008
  • 27
  • 37
Michael
  • 674
  • 1
  • 5
  • 13
  • possible duplicate of [Find all matching regex patterns and index of the match in the string](http://stackoverflow.com/questions/6178335/find-all-matching-regex-patterns-and-index-of-the-match-in-the-string) – Gajus Sep 13 '15 at 20:09

2 Answers2

20

The proper way to do this is not with an Array but an object:

var x = {};
x['Zero'] = 'Zero';
x['One'] = 'One';
x['Two'] = 'Two';
console.log(x); //  Object Zero=Zero One=One Two=Two
delete x['One'];
console.log(x); //  Object Zero=Zero Two=Two
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • @Daniel - no it doesn't, that's not modifying the array. Do arr.length after adding your value and before deleting it. – Paolo Bergantino Feb 14 '17 at 20:50
  • @Daniel You are confusing Objects and Arrays, and then within arrays the differences between delete vs splice: http://stackoverflow.com/questions/500606/deleting-array-elements-in-javascript-delete-vs-splice – Paolo Bergantino Feb 28 '17 at 14:32
  • No, not confusing. Just did not know how it works. But the link you posted gives a good explanation. Very helpful in this threat. – Daniel Mar 01 '17 at 06:31
5

Once an Array has string keys (or numbers that don't follow), it becomes an Object.

An object doesn't have the splice method (or not the same as Array). You have to write your own, by making a new object and copy into it the key you want to keep.

But be careful ! The keys are not always ordered in the same way they were added in the object ! It depends on the browser.

Fabien Ménager
  • 140,109
  • 3
  • 41
  • 60