Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to delete one entry from the middle of Array()

What is the fastest way to delete one specific entry from the middle of Array()

Array is large one having Strings.

I dont want just to set Array[5] = null, but instead array size should be reduced by one and array[5] should have content of array[6] etc.

like image 216
Tom Avatar asked Mar 12 '09 12:03

Tom


People also ask

How do I remove an item from the middle of an array?

You can remove elements from the end of an array using pop, from the beginning using shift, or from the middle using splice. The JavaScript Array filter method to create a new array with desired items, a more advanced way to remove unwanted elements.

How do you remove one index from an array?

Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.

Which method is used to remove first element of an array pop () remove () shift () delete ()?

The shift() method removes the first item of an array.

What is the complexity of removing an item from the middle of an array?

Yes. It takes O(n) time to find the element you want to delete. Then in order to delete it, you must shift all elements to the right of it one space to the left. This is also O(n) so the total complexity is linear.


1 Answers

Don't have any benchmarks to support this, but one would assume that the native Array.splice method would be the fastest...

So, to remove the entry at index 5:

array.splice(5, 1); 
like image 197
kkyy Avatar answered Oct 03 '22 02:10

kkyy