Friday, 21 July, 2017 UTC


Summary

Deleting a particular element in a JavaScript array is pretty easy and there is various method that can be employed for the same. Let’s get our hands wet in order to understand how to delete elements in a JavaScript Array.

Using Delete in Order to Delete an Item from JavaScript Array

You can simply use delete in order to
delete
. This way you can delete the element from an array but the slot in an array goes
undefined
. Follow the code below
// Array of Fruits
var fruits = ['apple','mango','banana','orange'];

// Using Delete to delete the Value from the array
delete fruits[2];

// Printing the value of the Fruits
console.log(fruits)
See the code running below. You can see that the element got deleted but space leaves a blank space in the array.

Using Splice in order to delete an element from JavaScript Array

Using splice can solve the above issue. You can go ahead and follow this code in order to delete the element from the Array. Splice he helpful and helps you to delete the slot as well as the element. Have a look at the code.
// Array of Fruits
var fruits = ['apple','mango','banana','orange'];

// Function that takes the index of the element to be deleted
function deleteElement(elementIndex){
  fruits.splice(elementIndex,1);
  console.log(fruits);
}

// Calling the function to Delete Element from Array
deleteElement(2);
NOTE: Using Delete will create an empty slot in the Array and this will lead to the element deletion but the slot becomes empty.
The post How to delete an Element form a JavaScript Array? appeared first on The Web Juice.