Created
March 24, 2022 06:09
-
-
Save AnkitMaheshwariIn/b9bb5193cbf2a0c2ed689fb475befd45 to your computer and use it in GitHub Desktop.
Code to delete last element from an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* RUN THIS CODE AND OPEN YOUR CONSOLE TO SEE THE OUTPUT */ | |
// Code to delete last element from an array | |
// declare an array | |
arr = [10, 20, 30, 40, 50, 60] | |
console.log("To print elements before deletion") | |
for (i = 0; i < arr.length; i++) { | |
console.log(`Element at index ${i} is ${arr[i]}`) | |
} | |
// to remove last element of an array | |
// the index value of last index will be array length minus one | |
const index = arr.length - 1 | |
// splice an element from an array by index | |
if (index > -1) { | |
arr.splice(index, 1) // 2nd param is 1 means remove one element from an array starting from given index | |
} else { | |
console.log("Element not found in array") | |
} | |
console.log("To print elements after deletion") | |
for (i = 0; i < arr.length; i++) { | |
console.log(`Element at index ${i} is ${arr[i]}`) | |
} | |
/* | |
THE OUTPUT IS: | |
"To print elements before deletion" | |
"Element at index 0 is 10" | |
"Element at index 1 is 20" | |
"Element at index 2 is 30" | |
"Element at index 3 is 40" | |
"Element at index 4 is 50" | |
"Element at index 5 is 60" | |
"To print elements after deletion" | |
"Element at index 0 is 10" | |
"Element at index 1 is 20" | |
"Element at index 2 is 30" | |
"Element at index 3 is 40" | |
"Element at index 4 is 50" | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment