Created
March 24, 2022 06:06
-
-
Save AnkitMaheshwariIn/4c950d601963bd7c9727c643258e57f1 to your computer and use it in GitHub Desktop.
Code to delete first 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 first 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 first element of an array | |
// the index value of first index will be 0 | |
const index = 0 | |
// 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 20" | |
"Element at index 1 is 30" | |
"Element at index 2 is 40" | |
"Element at index 3 is 50" | |
"Element at index 4 is 60" | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment