Array
Welcome to the Array section of JDCodebase! Arrays are one of the most fundamental and frequently used data structures in programming...
What You’ll Learn
- Traversal, insertion, and deletion basics
- Prefix sums, difference arrays, sliding windows
- Sorting, searching, and pointer-based optimizations
JavaScript Array Methods
arr.push(val): Adds an element to the end of the array.
Before: [1, 2] Code: arr.push(3); After: [1, 2, 3]
arr.pop(): Removes the last element.
Before: [1, 2, 3] Code: arr.pop(); After: [1, 2]
arr.shift(): Removes the first element of the array.
Before: [10, 20, 30] Code: arr.shift(); After: [20, 30]
arr.unshift(val): Adds one or more elements to the beginning.
Before: [2, 3] Code: arr.unshift(1); After: [1, 2, 3]
arr.slice(start, end): Returns a shallow copy of a portion of the array.
Before: [10, 20, 30, 40] Code: arr.slice(1, 3); After: [20, 30]
arr.splice(index, count, ...items): Adds/removes items to/from the array at a specific index.
Before: [1, 2, 4] Code: arr.splice(2, 0, 3); After: [1, 2, 3, 4]
arr.includes(val): Checks if the array contains the specified value.
Before: [1, 2, 3] Code: arr.includes(2); After: true
arr.indexOf(val): Returns the first index of the specified value, or -1.
Before: [1, 2, 3, 2] Code: arr.indexOf(2); After: 1
arr.sort(): Sorts the array as strings by default.
Before: [3, 1, 2] Code: arr.sort(); After: [1, 2, 3]
arr.reverse(): Reverses the elements of the array in place.
Before: [1, 2, 3] Code: arr.reverse(); After: [3, 2, 1]
Try This Example
Let’s reverse an array using a loop.
function reverseArray(arr) { let result = []; for (let i = arr.length - 1; i >= 0; i--) { result.push(arr[i]); } return result; }
Input: [1, 2, 3]
Expected Output: [3, 2, 1]