Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript splicing array

Tags:

javascript

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.

like image 693
frenchie Avatar asked Nov 16 '11 21:11

frenchie


People also ask

What is array splice in JavaScript?

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.

Can you slice an array in JavaScript?

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.

How do you splice an array function?

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() .

How do you splice an element from an array?

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.


1 Answers

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"]
like image 112
Jon Newmuis Avatar answered Oct 14 '22 21:10

Jon Newmuis