How can I remove a specific item from an array in JavaScript?

clock icon

asked 5 months ago Asked

message

1 Answers

eye

21 Views

How do I remove a specific value from an array? Something like:

array.remove(value);

 

Constraints: I have to use core JavaScript. Frameworks are not allowed.

1 Answers

 

There are two major approaches

  1. splice()anArray.splice(index, 1);

    let fruits = ['Apple', 'Banana', 'Mango', 'Orange']
    let removed = fruits.splice(2, 1);
    // fruits is ['Apple', 'Banana', 'Orange']
    // removed is ['Mango']
    
  2. deletedelete anArray[index];

    let fruits = ['Apple', 'Banana', 'Mango', 'Orange']
    let removed = delete fruits(2);
    // fruits is ['Apple', 'Banana', undefined, 'Orange']
    // removed is true
    

Be careful when you use the delete for an array. It is good for deleting attributes of objects, but not so good for arrays. It is better to use splice for arrays.

Keep in mind that when you use delete for an array you could get wrong results for anArray.length. In other words, delete would remove the element, but it wouldn't update the value of the length property.

You can also expect to have holes in index numbers after using delete, e.g. you could end up with having indexes 1, 3, 4, 8, 9, and 11 and length as it was before using delete. In that case, all indexed for loops would crash, since indexes are no longer sequential.

If you are forced to use delete for some reason, then you should use for each loops when you need to loop through arrays. As the matter of fact, always avoid using indexed for loops, if possible. That way the code would be more robust and less prone to problems with indexes.

Write your answer here