TypeScript array operations: Add, remove, iterate
TypeScript Basic: Exercise-8 with Solution
Write a TypeScript program that declares an array of a specific data type. It will demonstrates common array operations like adding elements, removing elements, and iterating through the array.
Sample Solution:
TypeScript Code:
// Declare an array of strings
const colors: string[] = ["Red", "Green", "Blue", "Orange"];
// Add elements to the array
colors.push("White");
colors.push("Pink");
// Remove elements from the array
colors.pop(); // Removes the last element ("Orange")
// Iterate through the array and print each element
console.log("Array Elements:");
for (const c of colors) {
console.log(c);
}
// Check if an element exists in the array
const searchColor = "Green";
const isColorInArray = colors.includes(searchColor);
console.log(`Is ${searchColor} in the array? ${isColorInArray ? "Yes" : "No"}`);
// Find the index of a specific element in the array
const indexOfBlue = colors.indexOf("Blue");
console.log(`Index of "Blue" in the array: ${indexOfBlue}`);
// Remove a specific element from the array by index
if (indexOfBlue !== -1) {
colors.splice(indexOfBlue, 1);
}
// Display the modified array
console.log("Modified Array:");
console.log(colors);
Explanations:
In the exercise above -
- First, we declare an array "colors" of type string[] and initialize it with string values representing color names.
- We use the "push()" method to add elements ("White" and "Pink") to the end of the array.
- We use the "pop()" method to remove the last element ("Pink") from the array.
- We iterate through the array using a for...of loop and print each element to the console.
- We use the includes method to check if a specific element ("Green") exists in the array.
- We use the indexOf method to find the index of a specific element ("Blue") in the array.
- If we find the index of "Blue", we use the "splice()" method to remove it from the array.
- Finally, we display the modified array.
Output:
"Array Elements:" "Red" "Green" "Blue" "Orange" "White" "Is Green in the array? Yes" "Index of \"Blue\" in the array: 2" "Modified Array:" ["Red", "Green", "Orange", "White"]
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript type aliases for improved readability.
Next: TypeScript Enumeration: Define and Assign Values.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics