0

tl;dr; Even without my explanation one can look at the code below and the output and see something is fishy. Splice returns the index it spliced but the data remains in the array.

So I have an object that's keyed almost like an array (0,1,2,3...etc). Each object key has an array value. The array is an array of objects. Here's a simplified object that shows the basic structure I'm working with:

obj = {
    '1': [{},{},{},{}],
    '2': [{},{},{},{}],
    '3': [{},{},{},{}]
};

I have some code that needs to splice out one of the array indices (objects) from one of those arrays. This is the code, with console logging around everything (which I will show the output of below).

console.log(indices_to_remove);
for(j = 0; j < indices_to_remove.length; j++) {
    console.log("i: " + i)
    console.log('j: ' + j)
    console.log(this._index);
    console.log(this._index[i].splice(indices_to_remove[j], 1));
    console.log(this._index);
}

Notice on the second "console.log(this._index);" the spliced object is still part of the original array. I would assume that this._index[2] would now have one less item. Also, I should be splicing out index 0, yet it returns index 1.

Here's the output: Console

So if anyone has any insight into what I might be doing wrong please speak up!

Thanks, Mike

3
  • JSON is great but I can't really re-write everything to support that right now. My question is really why splice seems to be malfunctioning in this case. Commented Dec 9, 2009 at 8:09
  • @yoda: What has JSON got to do with this? Commented Dec 9, 2009 at 9:22
  • 2
    He's declaring his arrays using array and object literals. That it looks like JSON (a data format) is incidental. The question would be the same if it was written out using new Array(...) and new Object() instead. Commented Dec 9, 2009 at 10:29

1 Answer 1

4

There is a lot missing in the code that you are showing, so I had to do some guessing. I ran this code, and it works as expected:

var obj = {
    '1': [{},{},{},{}],
    '2': [{},{},{},{}],
    '3': [{},{},{},{}]
};

var indices_to_remove = [1];

var i = 1;
alert(indices_to_remove);
for(j = 0; j < indices_to_remove.length; j++) {
    alert("i: " + i)
    alert('j: ' + j)
    alert(obj[i]);
    alert(obj[i].splice(indices_to_remove[j], 1));
    alert(obj[i]);
}

However, you should consider looping backwards in the array of indexes to remove. When you have removed the first item, the second item is now the first item. If you then remove the second item, it's really the third item that you remove.

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.