Skip to content

Instantly share code, notes, and snippets.

@AnkitMaheshwariIn
Created March 24, 2022 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AnkitMaheshwariIn/a49f1ef0a36d38e515eeb9a20d88a175 to your computer and use it in GitHub Desktop.
Save AnkitMaheshwariIn/a49f1ef0a36d38e515eeb9a20d88a175 to your computer and use it in GitHub Desktop.
Code to delete element at a specific position from an array
/* 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