Monday, July 20, 2020

Remove Elements From An Array With Javascript

Remove Elements From An Array With Javascript


There are 2 main methods of removing an element from an array in javascript, splice and delete.
I’ll discuss both methods, provide examples and detail out the benefits and drawbacks of each.

.splice()


  1. var myArray = ["dog", "cat", "fish", "duck"];
  2.  
  3. var itemToRemove = "fish";
  4. var indexOfItemToRemove;
  5.  
  6. //use indexOf to determine the position in the array that the item appears
  7. indexOfItemToRemove = myArray.indexOf(itemToRemove);
  8.  
  9.  
  10. //Use the splice method of your array object, passing in the index of the item you want to remove and how many occurances of that item you want to remove
  11. //splice removed the elements from the array in-place and outputs an array of items that it removed
  12. //splice will completely remove the element from the array, leaving no empty array positions
  13. var removedItems;
  14. if (indexOfItemToRemove > -1) {
  15. removedItems = myArray.splice(indexOfItemToRemove, 1);
  16. }
  17.  
  18. alert("indexOfItemToRemove = " + indexOfItemToRemove +
  19. " removedItems Count = " + removedItems.length +
  20. " myArray Length = " + myArray.length);

Using splice, you will remove the element from the array, and it will return an array of items that were removed.
The array is modified in-place, meaning that when the elements are removed from the array the elements after the one that was just removed shift forwards, which updates their indexes and the length property of the array.
This means that if you plan to use the iterative method in order to remove the elements from the array you will need to iterate through it backwards.

  1. var removedItems;
  2. for (var i = myArray.length; i--;) {
  3. if (myArray[i] == itemToRemove) {
  4. removedItems = myArray.splice(i, 1);
  5. }
  6. }
  7.  
  8. alert("count in myArray =" + myArray.length
  9. + " count of removed items from array=" + removedItems.length);

If you try to iterate forwards, not only will you certainly be accessing the incorrect item in the array, but you may even get an index out of range error.
Suppose the item that was removed from the array was the second to last item in the array, when you get to the last item, the index position will be 1 out, because the last item’s index has reduced by 1.

If you decide to use the indexOf method to remove the elements from the array, you won’t have to worry about this, but keep in mind that the indexOf method doesn’t work for older browsers (IE 9+ and FireFox 1.5+).

If compatibility with older browsers isn’t a concern, I recommend you use the indexOf method as you don’t have to iterate over the array at all to remove a specific item.

However, if you need to remove many items from the array (like all instances of “fish” for example) you would have to iterate over the array, and in each iteration check if indexOf returns -1 ,indicating that the item you’re looking for isn’t in the array.
Alternatively you can use JQuery’s $.inArray() method (Discussed later).

  1. var i = myArray.indexOf(itemToRemove);
  2. while (i > -1) {
  3. myArray.splice(i, 1);
  4. i = myArray.indexOf(itemToRemove);
  5. }
  6.  
  7. alert("count in myArray =" + myArray.length
  8. + " index of item to remove " + myArray.indexOf(itemToRemove));

delete myArray[index]

  1. //this will completely remove this item but not update the indexes of the array items or the length property of the array.
  2. //the existing array is modified in-place, and is safe to iterate forwards
  3. for (var i = 0; i < myArray.length; i++) {
  4. if (myArray[i] == itemToRemove) {
  5. delete myArray[i];
  6. }
  7. }
  8.  
  9. alert("value of removed item is " + myArray[2])
  10.  
  11. alert("count in myArray =" + myArray.length
  12. + " index of item to remove " + myArray.indexOf(itemToRemove));

Using delete is the alternative method to remove an element from an array.

When you use the delete method it will remove the item from the array without changing the indexes of the other items in the array, but it also won’t update the length property as instead of removing the item from the array completely, it will instead leave an empty item.

Think of it like having a string variable and then setting it’s value to an empty string.  The variable still exists but it has no content.

If you try to access one of the deleted array items, it will return undefined.

JQuery - Getting An Item’s Index In An Array - $.inArray()

If you want to use indexOf() but need to be compatible with older browsers, you can use the $.inArray() method of JQuery.
Under the hood, If it determines that indexOf() is not possible, JQuery will be iterating over the array checking for matches, but it means that you don’t have to clutter your code with the loops, nor concern yourself with whether or not the user has an older browser which doesn’t support indexOf().

  1. var jqindexOfItemToRemove = $.inArray(itemToRemove, myArray);
  2. alert(jqindexOfItemToRemove);

The first parameter is the item you’re looking for, the second parameter is the array to search through.  The third parameter is the index to start iterating from, it default to zero so I’ve left it out of my example.
The result is the same as indexOf() in that the zero based index position is returned if the item is in the array and if it’s not in the array it will return -1.

If you enjoyed this article, please consider giving it a +1

Online Course

React Native Chat App with Firebase - Firestore Course 2020


This course is for every programmer who wants to learn mobile application development and want to increase their skills to the next level.

Online Course


This is a Beginner to Advanced course and perfectly suitable for anyone interested to learn jQuery effects and animations for their web projects. If you have basic knowledge of HTML, CSS, and JavaScript then you're good to go. After finish, you'll learn 12 really cool effects that you can use in your web projects. Moreover, using this knowledge you'll be able to do more interesting effects on your own. 


No comments:

Post a Comment

The 3 Most Popular Front-end Frameworks Compared

  There’s an outsized number of front-end frameworks available today, each with different strengths and weaknesses. This makes it tricky to ...