Arrays Deep Dive, Methods, Sorting Quirks & ES6+ (Masterclass)

๐ŸŸจ JavaScript (ES2026+) ๐ŸŸข Lesson 10 ๐Ÿ“‚ Phase 07: Arrays Masterclass ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this lesson: Array ante enti? ยท Indexes & Updating ยท length tricks ยท push/pop/shift/unshift ยท slice vs splice ยท includes/indexOf ยท join ยท reverse ยท sort() Quirks & Comparators ยท concat ยท Nested 2D Matrices ยท Array Destructuring ยท Spread & Rest ยท 5 Practice Algorithms

Welcome to Phase 7: Arrays Masterclass! In JavaScript, an Array is an ordered, dynamically-sized collection of values stored sequentially in memory. Unlike strict typed languages (like C or Java) where arrays have fixed sizes and require uniform data types, JavaScript arrays can store heterogeneous data types (Numbers, Strings, Objects, Functions, and other Arrays) and expand or shrink dynamically on demand.

1Array Ante Enti? & Creating Arrays

JavaScript lo Array ante multiple values ni single variable name kinda store cheyagala data structure. Internally, JS Arrays are specialized Objects where numeric indexes serve as keys and elements are placed in Heap memory.

1. Array Literal (Recommended โญ)

Square brackets [] tho direct ga elements define cheyyadam: const marks = [85, 90, 78, 92];

2. Array Constructor

new Array(5) โ€” โš ๏ธ Single number isthe 5 empty slots tho array create avthundhi, value kaadu!

3. Array.of() & Array.from()

Array.of(5) creates [5]. Array.from("JS") creates ['J', 'S'].

JavaScript โ€” Array Basics Example โ–ถ Run Code
"use strict";

const marks = [85, 90, 78, 92];

marks.push(88); // Adds 88 to the end

console.log("Marks Array:", marks);
console.log("First Element [0]:", marks[0]);
console.log("Total Count (length):", marks.length);
2Indexes, Reading, Updating & The length Mutation Trick

Arrays zero-indexed (0 to length - 1):

  • Reading Elements: marks[0] (first), marks.at(-1) (ES2022 last item). Out-of-bounds reading returns undefined.
  • Updating Elements: marks[1] = 95; updates index 1 in place.
  • Length Property & Truncation Trick: length property is writable! Setting marks.length = 2 truncates the array down to 2 items! Setting marks.length = 0 clears the entire array in memory!
JavaScript โ€” Length & Bounds Demo โ–ถ Run Code
"use strict";

let fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"];

console.log("Last Fruit (.at(-1)):", fruits.at(-1)); // "Grapes"

// Truncating array using length
fruits.length = 3;
console.log("After fruits.length = 3:", fruits); // ["Apple", "Banana", "Mango"]

// Clearing array in memory
fruits.length = 0;
console.log("After fruits.length = 0 (Cleared):", fruits); // []
3Mutator Methods: push(), pop(), unshift() & shift()

Original array structure ni direct ga modify chese core four methods:

MethodAction PositionReturn ValuePerformance (Time Complexity)
push(...items) Adds elements to END New array length $O(1)$ Constant Time โšก
pop() Removes element from END Removed element $O(1)$ Constant Time โšก
unshift(...items) Adds elements to START New array length $O(N)$ Linear Time (re-indexes all items)
shift() Removes element from START Removed element $O(N)$ Linear Time (shifts all items left)
JavaScript โ€” Stack & Queue Operations โ–ถ Run Code
"use strict";

let stack = [10, 20];

// Push & Pop (End)
stack.push(30); // [10, 20, 30]
console.log("Pushed 30 ->", stack);

let popped = stack.pop(); // Removes 30
console.log("Popped item:", popped, "| Current Stack:", stack);

// Unshift & Shift (Start)
stack.unshift(5); // [5, 10, 20]
console.log("Unshifted 5 ->", stack);

let shifted = stack.shift(); // Removes 5
console.log("Shifted item:", shifted, "| Current Stack:", stack);
4slice() vs splice() (The Crucial Interview Distinction)
1. slice(start, end) โ€” IMMUTABLE (Safe)
  • Original array ni modify cheyyadhu.
  • Returns a new shallow copy of specified range.
  • Negative indices support chesthundhi (e.g. arr.slice(-2)).
2. splice(start, deleteCount, ...items) โ€” MUTATING
  • Original array ni in-place ga modify chesthundi.
  • Items ni delete, replace, or insert cheyyadaniki vadathamu.
  • Returns an array of deleted elements.
JavaScript โ€” slice vs splice Code Comparison โ–ถ Run Code
"use strict";

const original = ["A", "B", "C", "D", "E"];

// 1. slice() does NOT change original
const sliced = original.slice(1, 4);
console.log("Sliced (1 to 4):", sliced);       // ["B", "C", "D"]
console.log("Original untouched:", original);  // ["A", "B", "C", "D", "E"]

// 2. splice() modifies original array
// Syntax: splice(startIndex, deleteCount, insertItem1, insertItem2...)
const deleted = original.splice(2, 2, "NEW_C", "NEW_D");
console.log("Deleted by splice:", deleted);    // ["C", "D"]
console.log("Original mutated:", original);    // ["A", "B", "NEW_C", "NEW_D", "E"]
5Search & Transform: includes, indexOf, join, reverse & concat
  • includes(val): Returns true if element exists (handles NaN correctly).
  • indexOf(val): Returns first matching index or -1.
  • join(separator): Array elements ni custom string delimiter tho join chesthundi (e.g. ["a","b"].join("-") -> "a-b").
  • reverse(): Reverses the array elements in place (mutates original).
  • concat(...arrays): Combines multiple arrays into a fresh new array without mutating originals.
JavaScript โ€” Search & Transform Methods โ–ถ Run Code
"use strict";

const fruits = ["Apple", "Mango", "Banana"];

console.log("Has 'Mango'?", fruits.includes("Mango")); // true
console.log("Index of 'Banana':", fruits.indexOf("Banana")); // 2
console.log("Joined:", fruits.join(" โž” ")); // "Apple โž” Mango โž” Banana"

const reversed = fruits.reverse();
console.log("Reversed array:", reversed);

const numbers1 = [1, 2];
const numbers2 = [3, 4];
console.log("Concat:", numbers1.concat(numbers2, [5, 6])); // [1, 2, 3, 4, 5, 6]
6The sort() Method & Numeric Sorting Quirk (Deep Dive)
โš ๏ธ The Historic JavaScript Array sort() Quirk

JavaScript default sort() numbers ni direct ga sort cheyyadhu! Elements ni Strings ga convert chesi UTF-16 lexicographical (ASCII alphabetic) order lo sort chesthundi. Andhuke [10, 2, 30].sort() output [10, 2, 30] (or [10, 20, 2]) ga vasthundi, because string "10" comes before "2"!

Numeric values ni accurate ga sort cheyyadaniki Comparator Function (a, b) => a - b pass cheyyali:

JavaScript โ€” sort() Comparator Demo โ–ถ Run Code
"use strict";

const numbers = [10, 2, 30];

// โŒ Default string sort (Buggy for numbers!)
// numbers.sort(); // Output: [10, 2, 30]

// โœ… Correct Numeric Ascending Sort: (a, b) => a - b
numbers.sort((a, b) => a - b);
console.log("Ascending Sorted:", numbers); // [2, 10, 30]

// โœ… Correct Numeric Descending Sort: (a, b) => b - a
numbers.sort((a, b) => b - a);
console.log("Descending Sorted:", numbers); // [30, 10, 2]
7Nested Arrays (Multi-Dimensional 2D Matrices)

Oka array lopala maroka array unte dhaanni 2D Array / Nested Array antaru. Matrix row and column format lo data access avthundi:

JavaScript โ€” 2D Matrix Grid โ–ถ Run Code
"use strict";

const matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

console.log("Row 0, Col 0:", matrix[0][0]); // 1
console.log("Row 1, Col 1 (Center):", matrix[1][1]); // 5
console.log("Row 2, Col 2:", matrix[2][2]); // 9

// Flattening nested arrays with .flat()
const nested = [1, [2, [3, 4]]];
console.log("Flattened (depth 2):", nested.flat(2)); // [1, 2, 3, 4]
8Array Destructuring, Spread & Rest Operators
  • Array Destructuring: Unpacking array elements into clean individual variables: const [first, second] = arr;
  • Spread Operator (... Expanding): Unpacks array items into comma-separated elements (ideal for merging and shallow cloning).
  • Rest Operator (... Collecting): Gathers the remaining elements into a fresh array: const [leader, ...members] = team;
JavaScript โ€” Destructuring & Spread/Rest โ–ถ Run Code
"use strict";

const scores = [95, 88, 76, 62, 55];

// 1. Destructuring with Rest (...)
const [topper, runnerUp, ...others] = scores;
console.log("Topper:", topper);       // 95
console.log("Runner Up:", runnerUp);   // 88
console.log("Others Array:", others);  // [76, 62, 55]

// 2. Swapping variables in 1 line
let x = 10, y = 20;
[x, y] = [y, x];
console.log("Swapped: x =", x, ", y =", y);

// 3. Spread operator merging
const batch1 = ["Ravi", "Kiran"];
const batch2 = ["Sneha", "Pooja"];
const allStudents = [...batch1, ...batch2, "Vijay"];
console.log("All Students:", allStudents);
95 Real-World Practice Algorithms

Mastering arrays through 5 essential coding interview problems:

Program 1: Find Largest and Smallest in an Array

JavaScript โ–ถ Run Code
"use strict";

const data = [45, 12, 89, 3, 99, 24];

const maxVal = Math.max(...data);
const minVal = Math.min(...data);

console.log("Array:", data);
console.log("Max:", maxVal, "| Min:", minVal);

Program 2: Remove Duplicates from an Array

JavaScript โ–ถ Run Code
"use strict";

const duplicateNums = [1, 2, 2, 3, 4, 4, 5, 1];

// Clean 1-line solution using Set and Spread
const uniqueNums = [...new Set(duplicateNums)];

console.log("Original:", duplicateNums);
console.log("Unique:", uniqueNums); // [1, 2, 3, 4, 5]

Program 3: Rotate Array by K Positions

JavaScript โ–ถ Run Code
"use strict";

function rotateRight(arr, k) {
    const n = arr.length;
    const effectiveK = k % n;
    // Slice last k items and put in front
    return [...arr.slice(n - effectiveK), ...arr.slice(0, n - effectiveK)];
}

console.log("Rotated [1,2,3,4,5] right by 2:", rotateRight([1, 2, 3, 4, 5], 2));
// Output: [4, 5, 1, 2, 3]

Program 4: Element Frequency Counter

JavaScript โ–ถ Run Code
"use strict";

const votes = ["Ravi", "Sneha", "Ravi", "Kiran", "Ravi", "Sneha"];
const counts = {};

for (const vote of votes) {
    counts[vote] = (counts[vote] || 0) + 1;
}

console.log("Vote Counts:", counts);
// { Ravi: 3, Sneha: 2, Kiran: 1 }

Program 5: Matrix Diagonal Sum

JavaScript โ–ถ Run Code
"use strict";

const grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

let primaryDiagonalSum = 0;
for (let i = 0; i < grid.length; i++) {
    primaryDiagonalSum += grid[i][i]; // 1 + 5 + 9
}

console.log("Primary Diagonal Sum (1+5+9):", primaryDiagonalSum); // 15
๐Ÿ’ป Try It Yourself โ€” User Curriculum Code Example

Run this marks array and sorting comparator snippet in our live compiler:

JavaScript Arrays & Sorting โ–ถ Run Code
"use strict";

// Part 1: Marks Array
const marks = [85, 90, 78, 92];
marks.push(88);

console.log("Marks:", marks);
console.log("First Element:", marks[0]);
console.log("Length:", marks.length);

// Part 2: Numeric Sorting with Comparator
const numbers = [10, 2, 30];
numbers.sort((a, b) => a - b);
console.log("Sorted Numbers:", numbers);
Run Code in Our Compiler โ†’
OC
Written and reviewed by Our Compiler Technical Team ยท Updated for JavaScript ES2026+