Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Module 10: Advanced Arrays & Collections

1. The “Big Three” Iterators

These methods are the bread and butter of modern JS development. They allow you to process data without using old-fashioned for loops.

A. .map()

Transforms every element in an array and returns a new array of the same length.

JavaScript

const prices = [10, 20, 30];
const taxedPrices = prices.map(p => p * 1.1); // [11, 22, 33]

B. .filter()

Returns a new array containing only the elements that pass a specific test.

JavaScript

const ages = [12, 18, 25, 14];
const adults = ages.filter(age => age >= 18); // [18, 25]

C. .reduce()

Reduces an entire array down to a single value (like a sum, an object, or a string).

Syntax: array.reduce((accumulator, current) => { ... }, initialValue)

JavaScript

const cart = [5, 15, 10];
const total = cart.reduce((acc, price) => acc + price, 0); // 30

2. Advanced Array Search & Logic

  • .find(): Returns the first element that matches a condition.
  • .findIndex(): Returns the index of that first element.
  • .some(): Returns true if at least one element passes the test.
  • .every(): Returns true only if all elements pass the test.

JavaScript

const scores = [45, 80, 92];
const hasDistinction = scores.some(s => s > 90); // true
const allPassed = scores.every(s => s > 50);    // false

3. The Map Collection

While plain objects {} are great, a Map is a specialized collection for key-value pairs that offers better performance and flexibility.

Why use Map over Object?

  1. Any key type: Keys can be objects, functions, or primitives (Objects only allow strings/symbols).
  2. Order: Maps preserve the insertion order of keys.
  3. Size: You can get the size easily using .size.

JavaScript

const userRoles = new Map();
const user1 = { name: "Alice" };

userRoles.set(user1, "Admin");
console.log(userRoles.get(user1)); // "Admin"
console.log(userRoles.size);        // 1

4. The Set Collection

A Set is a collection of unique values. No duplicates are allowed.

Use Case: Removing duplicates from an array.

JavaScript

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)]; // [1, 2, 3, 4, 5]

5. WeakMap & WeakSet (Memory Management)

These are “weak” versions of Map and Set.

  • They only accept objects as keys/values.
  • They do not prevent Garbage Collection. If the only reference to an object is inside a WeakMap, JS will delete that object from memory.
  • This is useful for storing metadata about objects without causing “memory leaks.”

6. Flattening & Refactoring Arrays

Modern JS (ES2019+) introduced ways to handle nested arrays easily.

  • .flat(depth): Flattens nested arrays.
  • .flatMap(): Maps through an array and then flattens the result by one level.

JavaScript

const nested = [1, [2, [3]]];
console.log(nested.flat(2)); // [1, 2, 3]

💻 Technical Code Example: Data Transformation Pipeline

In real-world apps, you often chain these methods together to clean up raw data.

JavaScript

const inventory = [
    { item: "Laptop", price: 1000, stock: 5 },
    { item: "Mouse", price: 50, stock: 0 },
    { item: "Monitor", price: 300, stock: 10 }
];

// 1. Filter out out-of-stock items
// 2. Extract total value (price * stock)
// 3. Sum everything up
const totalInventoryValue = inventory
    .filter(p => p.stock > 0)
    .map(p => p.price * p.stock)
    .reduce((acc, val) => acc + val, 0);

console.log(totalInventoryValue); // 8000

In Simple words

1. Introduction to Arrays & Collections

Arrays and collections are core data structures used to:

  • Store grouped data
  • Optimize memory and performance
  • Enable efficient searching, sorting, and manipulation

Difference:

  • Arrays → fixed size, indexed
  • Collections → dynamic, flexible, feature-rich

2. Advanced Array Concepts

2.1 Memory Representation

  • Contiguous memory allocation
  • Direct index access (O(1))
  • Cache-friendly structure

2.2 Static vs Dynamic Arrays

FeatureStatic ArrayDynamic Array
SizeFixedResizable
PerformanceFasterSlight overhead
ExamplesC arraysArrayList, JS Array

2.3 Resizing Strategy (Amortized Analysis)

  • Capacity doubling
  • Copy cost spread across operations
  • Amortized O(1) insertion

3. Multidimensional Arrays

  • 2D / 3D arrays
  • Matrix representation
  • Jagged arrays vs rectangular arrays

Use cases:

  • Grids
  • DP tables
  • Game boards

4. Sparse Arrays

  • Large size, few elements
  • Memory optimization using maps or compressed storage
  • Common in ML & big data

5. Common Advanced Array Operations

  • Sliding window technique
  • Prefix sum
  • Two-pointer technique
  • Kadane’s algorithm
  • Binary search on arrays

6. Iteration Techniques

  • Index-based loops
  • Enhanced loops / for-each
  • Iterators
  • Streams (functional style)

7. Collection Framework Overview

Key Characteristics

  • Dynamic size
  • Built-in algorithms
  • Type safety (generics)
  • Multiple implementations

8. Core Collection Interfaces

InterfacePurpose
ListOrdered collection
SetUnique elements
QueueFIFO / priority
MapKey-value pairs

9. Advanced List Implementations

9.1 ArrayList / Dynamic Array

  • Fast random access
  • Slower middle insertions

9.2 LinkedList

  • Fast insert/delete
  • Slow access

9.3 Vector / Synchronized Lists

  • Thread-safe
  • Performance overhead

10. Advanced Set Implementations

HashSet

  • O(1) average operations
  • No ordering

LinkedHashSet

  • Maintains insertion order

TreeSet

  • Sorted
  • O(log n)

11. Advanced Queue Structures

Queue

  • FIFO

Deque

  • Double-ended queue

Priority Queue / Heap

  • Ordered by priority
  • Used in schedulers, Dijkstra

12. Map Implementations

HashMap

  • O(1) average
  • Unordered

LinkedHashMap

  • Insertion/access order

TreeMap

  • Sorted keys

ConcurrentHashMap

  • Thread-safe & scalable

13. Generics & Type Safety

  • Prevent runtime errors
  • Compile-time checks
  • Reusable code

14. Iterators & Fail-Fast Behavior

  • Concurrent modification detection
  • Iterator vs ListIterator
  • Safe removal patterns

15. Streams & Functional Operations

  • Map, filter, reduce
  • Lazy evaluation
  • Parallel processing

16. Sorting & Searching

Sorting Algorithms

  • TimSort
  • Merge sort
  • Quick sort

Custom Comparators

  • Multi-field sorting
  • Reverse ordering

17. Performance & Big-O Analysis

StructureAccessInsertSearch
ArrayO(1)O(n)O(n)
HashMapO(1)O(1)O(1)
TreeMapO(log n)O(log n)O(log n)

18. Memory & Optimization

  • Load factor
  • Initial capacity
  • Avoid resizing
  • Choose correct structure

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥