d0x
d0x

Reputation: 11571

Imutable delete/filter/remove Array Item by Index in Typescript

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

Answers (2)

jo_va
jo_va

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

d0x
d0x

Reputation: 11571

Imutable way with .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.

Mutable way with .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

Related Questions