7

I have an array of object and I'm looking to remove an element. However, the splice method seems to return the element removed, not the array without the element I wanted to remove.

This is what I have

var TheArray = TheObject.Array;
TheArray = TheArray.splice(TheIndex, 1); //TheIndex is the index of the element I want to remove
TheObject.Array = TheArrray;

When I debug and run this code, TheObject.Array contains the element I wanted to remove.

What am I doing wrong? Thanks for your suggestions.

2

3 Answers 3

16

splice returns the removed element, but modifies the element on which it was called. So in your example, TheArray is updated in place, and should no longer contain the removed element.

A more concrete, simplified example of how to use splice is as follows:

var myArr = ["a", "b", "c", "d"];
var elem = myArr.splice(2, 1);
// elem  => ["c"]
// myArr => ["a", "b", "d"]
Sign up to request clarification or add additional context in comments.

Comments

9

You are setting the value of TheArray to that of the item you are removing.

Rewrite your code like this:

var TheArray = TheObject.Array;
TheArray.splice(TheIndex, 1); //TheIndex is the index of the element I want to remove
TheObject.Array = TheArrray;

2 Comments

Those three lines of code can be replaced with TheObject.Array.splice(TheIndex,1).
Indeed they can but I wanted to keep the solution as simple as possible to understand. The asker should now know not to bother with the TheArray= part of his code. He can then work out the rest himself. :)
0

do an alert on your array to make sure the array is correct, also you may need to do a parseInt() around your variable (ie TheArray = TheArray.splice(parseInt(TheIndex), 1);) to make sure it's set to be an integer and not a string :)

i hope this helps

1 Comment

Then at least use parseInt(..., 10).

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.