Assuming I have the following array of objects:
var travelers = [
{
"name":"ana",
"lastname":"gomez"
},
{
"name":"juan",
"lastname":"gomez"
},
{
"name":"luis",
"lastname":"gomez"
},
{
"name":"pedro",
"lastname":"gomez"
}
];
I would like to know if there is a way to remove an object from the array in pure JavaScript or jQuery , by entering the position of the object to be removed.
You can use splice :
Syntax:
For example if you wanted to delete the third element of your array:
The array would look like this:
The nice thing about
splice
it is that you can get a sub-array containing what you've removed, i.e. you could save it for later if you wanted:The variable
elementoEliminado
would contain:For my part, I've used it on a few occasions as a kind of relocator, for example if you wanted to pass the first object to the last one as a kind of rotation:
Though I'm sure there are better ways.
Another option is to use the delete operator , but what this actually does is delete the property :
Syntax:
Example:
Now, if you wanted to access the first element, it would return
undefined
, but the index exists, unlikesplice
:You can use several methods to remove an element from it:
If you want to remove the element from x position, use:
you can also check this: JavaScript Array Reference
There are several ways to remove elements in javascript.
Array.prototype.splice
To use this method, the index of the element to be removed must be known.
Array.prototype.filter
This method was introduced in EcmaScript 5, using filter
Version for EcmaScript 5:
Version for EcmaScript 2015:
In Javascript there is the operator
delete
, which removes a property from an object (and in particular, can also remove an element in an array).The problem is that although it deletes the element from the array, it does not alter the other indices of the same array. For example: