0

I'm having trouble figuring how to delete an item from array where the items are indexed in a manner similar to the following:

arr[32] = 123
arr[39] = 456
arr[92] = 789
...

The two ways I have tried to delete single, specific items from said array have resulted in all items being removed.


Attempted Method #1:

arr.splice(39, 1);

Attempted Method #2:

arr.forEach(function(val, key) {
    if (val == 456) {
        arr.splice(key, 1);
    }
}

Now obviously this isn't exactly what my code looks like, but it shows what I've tried well enough. If I am missing any important details, or you want me to pick the code from source to see if it is within the source instead of the methodology, please ask

6
  • 2
    so you have a sparsed array and you like to delete an item. what went wrong? Commented Jan 13, 2017 at 22:14
  • 1
    @NinaScholz "The two ways I have tried ... have resulted in all items being removed." Commented Jan 13, 2017 at 22:15
  • 1
    Method 1 doesn't remove any other items. And neither does method 2. Commented Jan 13, 2017 at 22:18
  • Does your arr actually have items with index 0-92 as well, or is arr actually an object with keys? Removing an item from the array will change the indexes and could be causing other issues with your logic here. Commented Jan 13, 2017 at 22:19
  • 1
    As 4castle said, the code doesn't do what you claim. Please add a snippet, with which we can re-produce the issue. Commented Jan 13, 2017 at 22:31

1 Answer 1

2

While splicing changes the length of the array and the given array seems to rely on indices, you could just set the item to undefined.

var arr = [];

arr[32] = 123;
arr[39] = 456;
arr[92] = 789;

arr[39] = undefined;

console.log(arr[92]);

Sign up to request clarification or add additional context in comments.

Comments

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.