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.

frenchie
  • 51,731
  • 109
  • 304
  • 510

3 Answers3

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"]
Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57
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;
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

Robert Van Sant
  • 1,497
  • 10
  • 12