2

The thing is that I want to know, how delete operator deletes a value from an array. Does it loop for a whole array? What is the best way to delete and item from an array paying attention to time complexity.

Thanks for your answers.

5
  • 2
    Here to see what delete does. Commented Jan 14, 2021 at 21:43
  • @Countour-Integral I know what it does, but I want to know how it does that. Commented Jan 14, 2021 at 21:48
  • 3
    with code, what do you mean, you can take a look at the firefox source code or the chromium if you want to be more specific. Commented Jan 14, 2021 at 21:49
  • Define what you mean by deleting an item from array. There are multiple approaches and some are more efficient than others in terms of time complexity but might not do what you want. Commented Jan 14, 2021 at 22:04
  • The accepted answer is exactly what I needed. I just want to create a method to remove an item from a hashmap. Commented Jan 14, 2021 at 22:32

2 Answers 2

3

The delete operator just deletes all properties from an array element. Because looking up the element takes O(1) and deleting the properties takes O(1) the whole thing takes O(1). Be careful tho, delete does not change the length property of the array nor does it change the indexes of other elements within the array. So the behaviour is as follows:

const arr = [0,1,2,3,4,5]
delete arr[2]
console.log(arr[2]) // undefined

So delete is probably the best way in regards to time complexity, as methods utilizing splice or similar functions take O(n). Yet they are way safer.

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

1 Comment

Thanks, that was the answer that I needed. I will use it for hashmap, so it doesn't bother me, that it will be undefined, actually it is what I need. Thank you for your time!
0

To delete an element from an array, I have seen splice used most often with a delete_count passed as 1 (which means delete a single element).

let arr = [1, 2, 3];
arr.splice(0, 1); // delete `1` element starting at index `0`
// the above expression returns a new array containing the removed items
console.log(arr); // prints: [2, 3], since splice changes the array in place.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.