ποΈ Day 3: Arrays β Indexing, Iteration, and Basic Operations
π§ Concept Deep Dive
Arrays are one of the most fundamental data structures in computer science. They store items at contiguous memory locations and allow fast access using indices.
What is an Array?
- A data structure used to store elements of the same type.
- Elements are stored in contiguous memory and accessed via index.
- In TypeScript, arrays are dynamically sized.
- Arrays are often used when you need quick access to elements using a number (index) or when you need to loop over a list of data.
π Core Concepts
Indexing
- Access elements using their numeric index (starting from 0).
- If you try to access an index that doesn't exist, you get
undefined.const nums = [10, 20, 30]; console.log(nums[1]); // 20 console.log(nums[3]); // undefined
Iteration
- Loop through array elements with different methods:
const nums = [1, 2, 3];
// Traditional for loop for (let i = 0; i < nums.length; i++) { console.log(nums[i]); }
// for...of loop for (const num of nums) { console.log(num); }
// forEach method nums.forEach((num) => console.log(num));
### Length
- Use `.length` to get how many items are in the array.
```ts
console.log(nums.length); // 3Push/Pop
.push(x): Addsxto the end of the array.pop(): Removes the last elementnums.push(4); // [1, 2, 3, 4] nums.pop(); // [1, 2, 3]
Shift/Unshift
.shift(): Removes the first element.unshift(x): Addsxto the beginningnums.shift(); // [2, 3] nums.unshift(0); // [0, 2, 3]
Common Pitfalls
- Be careful with out-of-bound indexes.
- Mutating arrays (e.g., with
push,pop, etc.) changes the original array. - Use
slice()to copy arrays if you want to preserve the original.
π¨ ASCII Visualization
Array: [10, 20, 30, 40]
Index: 0 1 2 3
β β β β
10 20 30 40ποΈ Homework (LeetCode-style)
Problem 1: Get Last Element
function getLast(arr: number[]): number {
return arr[arr.length - 1];
}Input: [1, 2, 3] β Output: 3
Problem 2: Print All Elements
function printElements(arr: number[]): void {
arr.forEach(e => console.log(e));
}Input: [4, 5, 6] β Output: 4 5 6 (one per line)
Problem 3: Add Element to End
function addToEnd(arr: number[], value: number): number[] {
arr.push(value);
return arr;
}Input: ([1, 2], 3) β Output: [1, 2, 3]
Problem 4: Remove First Element
function removeFirst(arr: number[]): number[] {
arr.shift();
return arr;
}Input: [5, 6, 7] β Output: [6, 7]
Problem 5: Sum Elements
function sumElements(arr: number[]): number {
return arr.reduce((acc, val) => acc + val, 0);
}Input: [1, 2, 3, 4] β Output: 10
π Summary
- Arrays are ordered collections accessed via indices
- Basic operations include indexing, iteration, length access, and modification
- Arrays are mutable and commonly used in nearly every algorithm
π Coming Up
Day 4: Strings β Manipulation and Character Operations