Arrays in JavaScript are used to store multiple objects in a single object. These objects can be of different type like string, integer, json objects. We can access any object at n-index, we can replace or delete an object at n-index too. Most important point to remember is arrays are zero-indexed. The first object is at index 0. This post is all about deleting or removing an element from JavaScript array.
array.splice()
We can delete an item or object from a JavaScript array using array.splice() function. This takes two parameters:
- startIndex – Index of an object in the array.
- deleteCount – Number of items to be removed. (If this isn’t supplied, it removes all the object from the mentioned index).
Example:
Following example shows how to delete an object from JavaScript array using splice function:
let fruits = ["Apple", "Lychee","Mango","Orange","Pear","Pineapple"]; let fruits1 = [...fruits]; fruits.splice(2); document.write("Array contains: ", fruits); document.write("<br/><br/>"); fruits1.splice(2,1); document.write("Array contains: ", fruits1);
Output:
array.pop()
The pop() function removes the last object from an array.
let gadgets = ["Mobile","Earphones", "TWS", "Ultrabooks", "Powerbanks"]; let removedGadgets = gadgets.pop(); document.write("Array contains : ", gadgets); document.write("Removed object : ", removedGadgets);
Output:
array.shift()
array.shift() function removes the first element from JavaScript array.
Example:
let apps = ["TikTok","VS Code", "Notepad++", "XCode", "Snippy Tool", "Figma"]; let removedApp = apps.shift(); document.write("Useful Apps : ", apps); document.write("<br/><br/>"); document.write("Removed Apps : ", removedApp);
Output:
Also see:
How to create random color generator and picker in JavaScript
Create a simple Login form using only HTML and CSS
HTML JavaScript notifications using jQuery
Creating Digital Clocks using HTML, CSS and JavaScript