EN
TypeScript - remove specific array item by index
0
points
In this short article, we would like to show how to remove an item by index from an array in TypeScript.
Quick solution:
array.splice(itemIndex, 1); // removes item with index
Practical example
const removeItem = (array: string[], index: number): string => {
const removedItems = array.splice(index, 1);
if (removedItems.length > 0) {
return removedItems[0];
}
return undefined;
};
// Usage example:
// index: 0 1 2 3
const array: string[] = ['a', 'b', 'c', 'd'];
removeItem(array, 2); // removed 'c' item that has index 2
console.log(array); // [ 'a', 'b', 'd' ]
Output:
[ 'a', 'b', 'd' ]