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.
The splice() method is a built-in method for JavaScript Array objects. It lets you change the content of your array by removing or replacing existing elements with new ones. This method modifies the original array and returns the removed elements as a new array.
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end ( end not included) where start and end represent the index of items in that array.
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice() .
Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With