Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn’t deleting from a Javascript array change its length?

Tags:

javascript

I have an array:

data.Dealer.car[0]
data.Dealer.car[1]
data.Dealer.car[2]

If I do this:

alert(data.Dealer.car.length);
delete data.Dealer.car[1];
alert(data.Dealer.car.length);

It gives me the same count each time. Does the removed element still exist?

like image 602
joe90 Avatar asked Jan 30 '09 14:01

joe90


People also ask

Can you change the length of an array in JavaScript?

JavaScript allows you to change the value of the array length property. By changing the value of the length, you can remove elements from the array or make the array sparse.

Can you use Delete in an array in JavaScript?

JavaScript Array delete()Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.

What is time complexity for deleting an array?

If the element which needs to be deleted is present in arr[0], we need to shift all the elements from index 1 to size - 1 by position to the left. So it will take N - 1 iteration. For example, if the array has 100 elements the for loop will work for 99 times. Hence the time complexity will be O(N - 1).


1 Answers

If you want to remove an item, use the splice method:

alert(data.Dealer.car.length);
data.Dealer.car.splice(1, 1);
alert(data.Dealer.car.length);

But notice that the indices have changed.

like image 122
Gumbo Avatar answered Sep 21 '22 14:09

Gumbo