Languages
[Edit]
EN

TypeScript - remove element from array by index

0 points
Created by:
Hayley-Mooney
677

In TypeScript, it is not intuitive at the first time how to remove element by index. Remove the element by index operation can be achieved with Array.prototype.splice method. This article is focused on how to do it.

Quick solution:

array.splice(index, 1);  // removes 1 element

Where:

  • array - from this array we want to remove an element,
  • index - removed element index,
  • 1 - means the amount of the removed elements - we remove 1 element.

 

1. Practical example method example

//  index:                0    1    2    3
const array: string[] = ['a', 'b', 'c', 'd'];

// removes 3rd element
const removedElements: string[] = array.splice(2, 1); // removed from index: 2, removed elements amount: 1

console.log(array);
console.log(removedElements);

Output:

['a', 'b', 'd']
['c']

Array.prototype.splice(index, count) method:

  • takes:
    • index - starting from this index elements will be removed,
    • count - number of the elemnts to remove starting from index,
  • returns:
    • array with removed elements
  • warning:
    • splice() method middifies array

2. Reusable function

const removeItem = (array: string[], index: number): string => {
  const items: string[] = array.splice(index, 1);
  if (items.length > 0) {
    return items[0];
  }
  return null;
};

// Usage example:

//           index:       0    1    2    3
const array: string[] = ['a', 'b', 'c', 'd'];

const removedItem: string = removeItem(array, 2);

console.log(array);
console.log(removedItem);

Output:

['a', 'b', 'd']
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join