0

I have created an array:

myarray = new Array();
myarray['test_a'] = "test a";
myarray['test_b'] = "test b";

Now I would like to remove the entry with index "test_b". I tried this way:

var del = "test_b";
for(key in myarray){
   if(key==del){
      myarray.splice(key,1);
   }
}

However it does not work. No error. I just checked in firebug the entries for the array and mentioned that "test_b" still exists. What is wrong? Thanks for help.

2 Answers 2

5

Arrays are meant to have numeric indices, you want an object, then you can simply use delete:

var obj = {};
obj.test_a = "test a";
obj.test_b = "test b";

var del = "test_b";
delete obj[del];

console.log(obj); //=> { test_a: "test_a" }
Sign up to request clarification or add additional context in comments.

Comments

4

splice works on numerical index, what you have is that you have added a property to the array object. You can just do a delete to delete the property from the array object.

  delete myarray[del];

Demo

if you are just defining properties on an array and using it just as an object then better consider using an object instead of creating an array to store properties

2 Comments

This will absolutely work. It's important to know, however, that neither of the items have actually gone into the array. This is the wrong type of object to use in this circumstance.
@rescuecreative Yes of course, that is part of the usage, but there is no harm creating a property on the array object, some times you can store a hask key as a property to get a quick access to an index based on the value. But with the limited code in the post, not sure what he may be having originally.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.