How do I Remove an Array Item in TypeScript?
Last Updated :
01 Aug, 2024
In this article, we will learn about the different ways of removing an item from an array in TypeScript. In TypeScript, an array can be defined using union typing if it contains items of different types.
We can use the following methods to remove items from a TypeScript array:
Using the splice() method
The splice method can be used to delete multiple elements by specifying the start index from where the deletion of the element will start and the number of elements to be deleted as parameters to it. This method will return the removed elements.
Syntax:
const remItems = array.splice(startIndex, numberOfElementsToBeDeleted);
Example: The below code example will explain the use of the splice() method to delete elements from a TypeScript array.
JavaScript
const testingArr: (number | string)[] =
["JavaScript", 1, "GeeksforGeeks", 2, "TypeScript"];
console.log(`Initial Array: ${testingArr}`);
// Using the splice() method
const remItem = testingArr.splice(3, 2);
console.log(`Removed Items: ${remItem}`)
console.log(`Array After removing item: ${testingArr}`);
Output:
Initial Array: JavaScript, 1, GeeksforGeeks, 2, TypeScript
Removed Items: 2, TypeScript
Array After removing item: JavaScript, 1, GeeksforGeeks
Using the shift() method
The shift() method is used to remove the item from the start of an array and it returns the removed item as result. It requires no parameters.
Syntax:
const remItem = array.shift();
Example: The below example will explain the use of the shift() method to remove element from TypeScript array.
JavaScript
const testingArr: (number | string)[] =
["JavaScript", 1, "GeeksforGeeks", 2, "TypeScript"];
console.log(`Initial Array: ${testingArr}`);
// Using the shift() method
const remItem = testingArr.shift();
console.log(`Removed Item: ${remItem}`)
console.log(`Array After removing item: ${testingArr}`);
Output:
Initial Array: JavaScript, 1, GeeksforGeeks, 2, TypeScript
Removed Item: JavaScript
Array After removing item: 1, GeeksforGeeks, 2, TypeScript
Using the pop() method
The pop() method will delete the last element of the array without passing any parameter. It returns the removed element as a result.
Syntax:
const remItem = array.pop();
Example: The below example will explain the use of the pop() method to delete element from an array.
JavaScript
const testingArr: (number | string)[] =
["JavaScript", 1, "GeeksforGeeks", 2, "TypeScript"];
console.log(`Initial Array: ${testingArr}`);
// Using the pop() method
const remItem = testingArr.pop();
console.log(`Removed Item: ${remItem}`)
console.log(`Array After removing item: ${testingArr}`);
Output:
Initial Array: JavaScript, 1, GeeksforGeeks, 2, TypeScript
Removed Item: TypeScript
Array After removing item: JavaScript, 1, GeeksforGeeks, 2
Using filter() method
The filter() method filter the array based on the condition of the passed callback function. It returns a new array with new length and new elements.
Syntax:
const newArr = array.filter(() => {});
Example: The below code implements the filter() method to remove element at 4th index from the TypeScript array.
JavaScript
const testingArr: (number | string)[] =
["JavaScript", 1, "GeeksforGeeks", 2, "TypeScript"];
console.log(`Initial Array: ${testingArr}`);
// Using the fiter() method
const newArr = testingArr.filter((ele, ind) => ind !== 4);
console.log(`Removed Item: ${testingArr[4]}`);
console.log(`Array After removing item: ${newArr}`);
Output:
Initial Array: JavaScript, 1, GeeksforGeeks, 2, TypeScript
Removed Item: TypeScriptArray
After removing item: JavaScript, 1, GeeksforGeeks, 2
Using the delete operator
The delete operator can also be used to delete the array items in TypeScript.
Syntax:
delete array_name[deletingItemIndex];
Example: The below example explain the use of the delete operator to remove the item from an array in TypeScript.
JavaScript
const testingArr: (number | string)[] =
["JavaScript", 1, "GeeksforGeeks", 2, "TypeScript"];
console.log(`Initial Array: ${testingArr}`);
// Using delete operator
console.log(`Removed Item: ${testingArr[0]}`);
delete testingArr[0];
console.log(`Array After removing item: ${testingArr}`);
Output:
Initial Array: JavaScript, 1, GeeksforGeeks, 2, TypeScript
Removed Item: JavaScript
Array After removing item: , 1, GeeksforGeeks, 2, TypeScript
Using the slice() method
The slice() method can be utilized to remove an item from an array by creating a new array without the item to be removed. This method is useful when you want to keep the original array intact and obtain a modified array without modifying the original one.
Syntax:
const newArray = [...array.slice(0, indexToRemove), ...array.slice(indexToRemove + 1)];
Example: The following code demonstrates the use of the slice() method to remove an item from a TypeScript array.
JavaScript
const testingArr: (number | string)[] = ["JavaScript", 1, "GeeksforGeeks", 2,
"TypeScript"];
console.log(`Initial Array: ${testingArr}`);
// Using the slice() method
const indexToRemove = 3;
const newArray = [...testingArr.slice(0, indexToRemove), ...testingArr.slice(
indexToRemove + 1)];
const removedItem = testingArr[indexToRemove];
console.log(`Removed Item: ${removedItem}`);
console.log(`Array After removing item: ${newArray}`);
Output:
"Initial Array: JavaScript,1,GeeksforGeeks,2,TypeScript"
"Removed Item: 2"
"Array After removing item: JavaScript,1,GeeksforGeeks,TypeScript"
Using the reduce() Method
Another approach to remove an item from an array in TypeScript is by using the reduce() method. This method processes the array elements and builds a new array by accumulating values that meet a specific condition.
Example: Below is an example demonstrating how to use the reduce() method to remove an item from an array based on a specific condition.
JavaScript
const initialArray = ["JavaScript", 1, "GeeksforGeeks", 2, "TypeScript"];
const indexToRemove = 3;
const newArray = initialArray.reduce((acc, item, index) => {
if (index !== indexToRemove) {
acc.push(item);
}
return acc;
}, []);
console.log("Initial Array:", initialArray);
console.log("Array After removing item:", newArray);
Output:
Initial Array: [ 'JavaScript', 1, 'GeeksforGeeks', 2, 'TypeScript' ]
Array After removing item: [ 'JavaScript', 1, 'GeeksforGeeks', 'TypeScript' ]
Similar Reads
TypeScript Tutorial TypeScript is a superset of JavaScript that adds extra features like static typing, interfaces, enums, and more. Essentially, TypeScript is JavaScript with additional syntax for defining types, making it a powerful tool for building scalable and maintainable applications.Static typing allows you to
8 min read
Difference between TypeScript and JavaScript Ever wondered about the difference between JavaScript and TypeScript? If you're into web development, knowing these two languages is super important. They might seem alike, but they're actually pretty different and can affect how you code and build stuff online.In this article, we'll break down the
4 min read
TypeScript Interview Questions and Answers TypeScript, a robust, statically typed superset of JavaScript, has become a go-to language for building scalable and maintainable applications. Developed by Microsoft, it enhances JavaScript by adding static typing and modern ECMAScript features, enabling developers to catch errors early and improve
15+ min read
TypeScript Map TypeScript Map is a collection that stores key-value pairs, where keys and values can be of any type. It maintains the insertion order of keys and provides methods to add, retrieve, check, remove, and clear entries, ensuring efficient management of key-value data.Creating a MapA map can be created a
3 min read
Typescript Set A Set in TypeScript is a bunch of unique values. It is part of the ECMAScript 2015 (ES6) standard and is implemented as a native object in JavaScript.Unlike arrays, sets do not allow duplicate elements, making them useful for storing collections of unique items. TypeScript provides strong typing for
3 min read
TypeScript Array map() Method The Array.map() is an inbuilt TypeScript function that creates a new array with the results of calling a provided function on every element in the array.Syntax:array.map(callback[, thisObject])Parameters: This method accepts two parameters as mentioned above and described below: callback: This param
2 min read
Introduction to TypeScript TypeScript is a syntactic superset of JavaScript that adds optional static typing, making it easier to write and maintain large-scale applications.Allows developers to catch errors during development rather than at runtime, improving code reliability.Enhances code readability and maintainability wit
5 min read
How to Format Date in TypeScript ? Formatting dates is important especially when displaying them to the users or working with date-related data. TypeScript provides various ways to achieve this. Below are the methods to format the date data type in TypeScript:Table of ContentUsing toLocaleString() methodUsing toLocaleDateString() met
3 min read
Data types in TypeScript In TypeScript, a data type defines the kind of values a variable can hold, ensuring type safety and enhancing code clarity.Primitive Types: Basic types like number, string, boolean, null, undefined, and symbol.Object Types: Complex structures including arrays, classes, interfaces, and functions.Prim
3 min read
How to install TypeScript ? TypeScript is a powerful language that enhances JavaScript by adding static type checking, enabling developers to catch errors during development rather than at runtime. As a strict superset of JavaScript, TypeScript allows you to write plain JavaScript with optional extra features. This guide will
3 min read