Question:
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 remove.
Answer:
You can use splice :
Syntax:
array.splice (start, deleteCount [, item1 [, item2 [, …]]])
For example if you wanted to delete the third element of your array:
travelers.splice(2, 1)
The array would look like this:
var travelers = [
{
"name":"ana",
"lastname":"gomez"
},
{
"name":"juan",
"lastname":"gomez"
},
{
"name":"pedro",
"lastname":"gomez"
}
];
The good thing about splice
is that you can get a sub-array that contains what you have deleted, that is, you could save it for later if you wanted:
var elementoEliminado = travelers.splice(2, 1);
The variable elementoEliminado
would contain:
[
{
"name":"luis",
"lastname":"gomez"
}
]
For my part, I have used it on some occasions as a type of relocator, for example, if you wanted to pass the first object to the last as a kind of rotation:
> var array = [1,2,3,4,5]
> array.push(array.splice(0, 1)[0])
> array
[2, 3, 4, 5, 1]
> array.push(array.splice(0, 1)[0])
> array
[3, 4, 5, 1, 2]
Although 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:
delete expression
Example:
delete travelers[0];
Now, if you wanted to access the first element, it would return undefined
, but the index exists, unlike splice
:
travelers[0] // undefined