-3
arr = [
 {
   id:1
 },
 {
   id:2
 }
]

This is an example object structure. I want to delete first object in this array.

 delete arr[0];

Resulting structure is

[
{
  undefined * 1
},
{
  id:2
}
]

I have searched a lot and found that deleting an entire object will lead to dangling pointer problems. But i want resulting array to have only one object after deletion. Is there any other way to achieve this?

EDIT How to do if the object is neither first nor last?

Gibbs
  • 21,904
  • 13
  • 74
  • 138

3 Answers3

2

You need to create a shorter array instead. To remove the first element, just slice the array:

arr = arr.slice(1);

When the previous array is discarded the first element will also be discarded.

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
1

The only way to delete anything from an array is to resize it

arr = arr.slice(1)
James
  • 80,725
  • 18
  • 167
  • 237
1

You could, as an alternative to Array.prototype.slice(), use array.prototype.shift(), which simply removes the first element of the array:

arr = [
 {
   id:1
 },
 {
   id:2
 }
];

console.log(arr); // [Object, Object]

arr.shift();

console.log(arr); // [Object]

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410