-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?

2
  • arr.splice(x, 1) would be the generic solution. Commented Nov 12, 2014 at 11:44
  • Reason for downvoting pls. coz of duplicate? Which one is the duplicated copy Commented Nov 12, 2014 at 11:52

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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:

Comments

1

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

arr = arr.slice(1)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.