Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptDelete the array elements in JavaScript | delete vs splice

Delete the array elements in JavaScript | delete vs splice

This article will show you how to Delete the array element at a specific position using JavaScript. There are two approaches that can be used to delete elements in an array. They have their own merits regarding the way they perform the deletion. 

Delete array[index]:

This method deletes the element at the index specified but does not modify the array. This means that at the place of the deleted index, the element is left undefined or null. This may cause problems when iterating through the array as the deleted index does not hold any value. The length of the array in this case remains the same.

 Syntax:

delete array[index]

Example: In this example, we will be deleting an element at the 2nd index and display the resultant array using the delete method.

Javascript




// Function to delete element
function deleteElement() {
    // Input array
    let Arr = [1, 2, 3, 4, 5, 6];
     
    // Index of deleting element
    let index = 2;
    delete Arr[index];
     
    // Display output
    console.log(Arr);
}
 
deleteElement();


Output

[ 1, 2, <1 empty item>, 4, 5, 6 ]

JavaScript splice() Method

The array.splice() method is used to add or remove items from an array. This method takes in 3 parameters, the index where the element’s id is to be inserted or removed, the number of items to be deleted, and the new items which are to be inserted. This method actually deletes the element at the index and shifts the remaining elements leaving no empty index. This is useful as the array left after deletion can be iterated normally and displayed properly. The length of the array decreases using this method. 

Syntax:

array.splice(index, items_to_remove, item1 ... itemX)

Example: In this example, we will be deleting an element at the 2nd index and display the resultant array using the splice() method.

Javascript




// Function to delete element
function deleteElement() {
     
    //  Input array
    let Arr = [1, 2, 3, 4, 5, 6];
 
    // Index to delete element
    let index = 2;
    Arr.splice(index, 1);
 
    // Display output
    console.log(Arr);
}
 
deleteElement();


Output

[ 1, 2, 4, 5, 6 ]

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments