T030 Delving into Arrays and Collections
In this assignment, you’ll dive deeper into TypeScript’s array and collection capabilities. You’ll work with standard arrays, tuples, and maps, exploring various methods of declaration, manipulation, and iteration.
Setup
- Create a new TypeScript file
Arrays
- Initialization: Declare and initialize an array named
animalscontaining at least five different animal names. - Manipulation: Add a new animal to the end and another to the beginning of the
animalsarray. Then, remove the last animal and the first animal from the array. - Iteration: Use a
forloop to print each animal in theanimalsarray. Next, use theforEach()method to achieve the same result. - Functional Iteration: Use the
map()method to create a new array that contains each animal name in uppercase. Print this new array.
Generic Lists (Tuples)
- Declaration: Declare a tuple named
productthat contains a string (product name) and a number (price). - Array of Tuples: Create an array of tuples named
inventorycontaining at least threeproducttuples. - Access and Print: Use a
for-ofloop to print the name and price of each product in theinventory.
Dictionaries (Maps)
- Initialization: Create a
MapnamedstudentGradeswhere keys are student names (as strings) and values are their respective grades (as strings, e.g., “A”, “B”). - Adding Values: Add at least five key-value pairs to the
studentGradesmap. - Retrieval: Print the grade of a specific student using the
get()method. - Key Existence: Check if a particular student exists in the map using the
has()method. - Value Existence: Without using a built-in method, check if a specific grade (e.g., “B”) exists in the map. Print the result.
- Iteration: Use the
for-ofloop withentries()to print each student and their grade. Then, use theforEach()method to achieve the same result. - Functional Iteration: Use the
Array.from()method to convert the map’s values to an array. Then, use thefilter()method to create a new array containing only the students who have an “A” grade. Print this new array.
Once you’ve completed the assignment, you can compile the TypeScript file using the TypeScript compiler (tsc) to generate the corresponding JavaScript file. This will give you a chance to see how TypeScript transpiles to JavaScript.
Solution
Solution
Arrays
// Initialization
let animals: string[] = ["Lion", "Tiger", "Elephant", "Giraffe", "Zebra"];
// Manipulation
animals.push("Penguin");
animals.unshift("Kangaroo");
animals.pop();
animals.shift();
// Iteration using for loop
for (let i = 0; i < animals.length; i++) {
console.log(animals[i]);
}
// Iteration using forEach
animals.forEach(animal => console.log(animal));
// Functional Iteration using map
let uppercasedAnimals: string[] = animals.map(animal => animal.toUpperCase());
console.log(uppercasedAnimals);
Generic Lists (Tuples)
// Declaration
type Product = [string, number];
// Array of Tuples
let inventory: Product[] = [
["Laptop", 1000],
["Mouse", 20],
["Keyboard", 50]
];
// Access and Print using for-of loop
for (let item of inventory) {
console.log(`Product Name: ${item[0]}, Price: $${item[1]}`);
}
Dictionaries (Maps)
// Initialization
let studentGrades: Map<string, string> = new Map([
["Alice", "A"],
["Bob", "B"],
["Charlie", "A"],
["David", "C"],
["Eve", "B"]
]);
// Retrieval
console.log(`Alice's grade: ${studentGrades.get("Alice")}`);
// Key Existence
console.log(`Is Bob's grade available? ${studentGrades.has("Bob")}`);
// Value Existence
let hasBGrade: boolean = false;
for (let grade of studentGrades.values()) {
if (grade === "B") {
hasBGrade = true;
break;
}
}
console.log(`Is there a student with a B grade? ${hasBGrade}`);
// Iteration using for-of loop with entries
for (let [student, grade] of studentGrades.entries()) {
console.log(`${student} has a grade of ${grade}`);
}
// Iteration using forEach
studentGrades.forEach((grade, student) => {
console.log(`${student} has a grade of ${grade}`);
});
// Functional Iteration
let studentsWithAGrade: string[] = Array.from(studentGrades.entries()).filter(entry => entry[1] === "A").map(entry => entry[0]);
console.log(`Students with an A grade: ${studentsWithAGrade.join(", ")}`);