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?
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With