Reputation: 11571
How to delete an item by index in Typescript?
Like:
const myArray = ['a', 'b', 'c', 'd']
// how to remove index 2?
Upvotes: 1
Views: 2727
Reputation: 13963
You could use Array.prototype.slice() which is immutable and takes indices as arguments:
const arr = ['a', 'b', 'c', 'd'];
function removeAt(arr, i) {
return [...arr.slice(0, i), ...arr.slice(i+1)];
}
console.log(...removeAt(arr, 0));
console.log(...removeAt(arr, 1));
console.log(...removeAt(arr, 2));
console.log(...removeAt(arr, 3));
Upvotes: 3
Reputation: 11571
.filter()
You can use the .filter()
method to filter out the item at a given index.
const myArray = ['a', 'b', 'c', 'd']
const indexToDelete = 2
console.log( myArray.filter( (elem, i) => i !== indexToDelete) )
// Logs 'a', 'b', 'd'
This won't modify the original array.
.splice()
If you don't care that the original myArray
is modified, you can to it like this:
const myArray = ['a', 'b', 'c', 'd']
const indexToDelete = 2
myArray.splice(indexToDelete, 1)
console.log(myArray)
// Logs 'a', 'b', 'd'
Upvotes: 1