GIAIC - 04-Arrays and Strings
GIAIC - 04-Arrays and Strings
let arrayNameWithoutType=[]
let arrayName: type[];
let numbers = []; // 'numbers' is implicitly any[]
// Array of numbers:
let numbers: number[] = [1, 2, 3, 4];
// Array of strings:
let names: string[] = ["Alice", "Bob", "Charlie"];
// Using the Array type
let mixedArray: Array<number | string> = [1, "hello", 2];
Accessing and Modifying Array Elements using
[]
// Accessing elements by index:
let firstNumber = numbers[0]; // firstNumber will be 1
Adding elements:
.push(value) – Appends an element to the array's end.
.unshift(value) – Inserts an element at the array's beginning.
Removing elements:
.pop() – Removes and returns the last element from the array.
.shift() – Removes and returns the first element from the array.
Iterating through arrays:
for...of loop – A loop that iterates over the values in the array.
.forEach() method – A higher-order function that executes a provided function once
for each array element.
How Push and Unshift works in TypeScript
fruits.forEach((fruit) => {
console.log(fruit);
});
Iterating(Reading) the Elements of an Array In
TypeScript using For…Of loop
Using For…Of Loop to read the elements of an Array
// Looping through the 'fruits' array using a for...of //
loop:
for (let fruit of fruits) {
console.log(fruit); // Outputs: Apple, Orange,
// Banana
(each on a new line)
Advanced Array Methods
.find(callback):
This method searches the array for the first element that meets a specific condition
defined in a callback function. It returns the matching element or undefined if no
match is found.
.filter(callback):
This method creates a new array containing only the elements that pass a test
defined in a callback function.
.map(callback):
This method creates a new array by applying a callback function to each element of
the original array. The callback function transforms the element and the resulting
value is included in the new array.
Advanced Array Methods(.find(callback))