Created
March 24, 2022 06:00
-
-
Save AnkitMaheshwariIn/a49f1ef0a36d38e515eeb9a20d88a175 to your computer and use it in GitHub Desktop.
Code to delete element at a specific position 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 element at a specific position 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 element 40 from an array | |
// find index of element 40, | |
// index will be -1 if element not found in array | |
const index = arr.indexOf(40) | |
// 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 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