Arrays Deep Dive, Methods, Sorting Quirks & ES6+ (Masterclass)
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.
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.
Square brackets [] tho direct ga elements define cheyyadam: const marks = [85, 90, 78, 92];
new Array(5) โ โ ๏ธ Single number isthe 5 empty slots tho array create avthundhi, value kaadu!
Array.of(5) creates [5]. Array.from("JS") creates ['J', 'S'].
"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);
Arrays zero-indexed (0 to length - 1):
- Reading Elements:
marks[0](first),marks.at(-1)(ES2022 last item). Out-of-bounds reading returnsundefined. - Updating Elements:
marks[1] = 95;updates index 1 in place. - Length Property & Truncation Trick:
lengthproperty is writable! Settingmarks.length = 2truncates the array down to 2 items! Settingmarks.length = 0clears the entire array in memory!
"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); // []
Original array structure ni direct ga modify chese core four methods:
| Method | Action Position | Return Value | Performance (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) |
"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);
- Original array ni modify cheyyadhu.
- Returns a new shallow copy of specified range.
- Negative indices support chesthundhi (e.g.
arr.slice(-2)).
- Original array ni in-place ga modify chesthundi.
- Items ni delete, replace, or insert cheyyadaniki vadathamu.
- Returns an array of deleted elements.
"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"]
includes(val): Returnstrueif element exists (handlesNaNcorrectly).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.
"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]
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:
"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]
Oka array lopala maroka array unte dhaanni 2D Array / Nested Array antaru. Matrix row and column format lo data access avthundi:
"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]
- 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;
"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);
Mastering arrays through 5 essential coding interview problems:
Program 1: Find Largest and Smallest in an Array
"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
"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
"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
"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
"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
Run this marks array and sorting comparator snippet in our live compiler:
"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);