sajad torkamani

The below snippet is in TypeScript but you can use a very similar approach in other languages:

function removeElementAtIndex(arr: string[], index: number) {
  if (index >= arr.length) {
    console.warn(`No element exists at index: ${index}`)
    return
  }

  const previousElements = arr.slice(0, index)
  const subsequentElements = arr.slice(index + 1)

  return [...previousElements, ...subsequentElements]
}

const fruits = ['apple', 'orange', 'banana', 'pear', 'mango', 'kiwi']

console.log(removeElementAtIndex(fruits, 0)) // removes 'apple'
console.log(removeElementAtIndex(fruits, 1)) // removes 'orange'
console.log(removeElementAtIndex(fruits, 2)) // removes 'banana'

TypeScript playground

Tagged: Snippets