1. Basic Swap (Using Temporary Variable)
Concept: Use a temporary variable to hold one value during the swap.
// Step 1: Initialize array let fruits = ["🍎", "🍌", "🍊"]; // Step 2: Define swap positions const indexA = 0; // Apple const indexB = 2; // Orange // Step 3: Swap using a temporary variable const temp = fruits[indexA]; fruits[indexA] = fruits[indexB]; fruits[indexB] = temp; console.log(fruits); // Output: ["🍊", "🍌", "🍎"]
2. Destructuring Assignment (ES6)
Concept: Swap elements in one line using array destructuring.
let colors = ["red", "green", "blue"]; // Swap index 1 (green) and 2 (blue) [colors[1], colors[2]] = [colors[2], colors[1]]; console.log(colors); // Output: ["red", "blue", "green"]
3. Using splice()
for Complex Swaps
Concept: Remove and insert elements at specific positions.
let numbers = [1, 2, 3, 4]; // Swap index 0 (1) and index 3 (4) const removed = numbers.splice(0, 1); // Remove 1 element at index 0 → [1] numbers.splice(3, 0, removed[0]); // Insert removed element at index 3 console.log(numbers); // Output: [2, 3, 4, 1]
4. Advanced: Swap Function with Validation
Create a reusable function that validates indices before swapping:
function swapArrayElements(arr, index1, index2) { if ( index1 < 0 || index2 < 0 || // Negative indices index1 >= arr.length || // Indices out of bounds index2 >= arr.length ) { console.error("Invalid indices!"); return arr; // Return original array } [arr[index1], arr[index2]] = [arr[index2], arr[index1]]; // Destructure swap return arr; } // Test const animals = ["🐶", "🐱", "🐭", "🐹"]; swapArrayElements(animals, 1, 3); // Swap cat and hamster console.log(animals); // Output: ["🐶", "🐹", "🐭", "🐱"]
5. Real-World Example: Sorting Adjacent Elements
Swap adjacent elements to "bubble" a value up/down (e.g., simple sorting):
let scores = [50, 30, 40, 20]; // Bubble up: Swap lower value to the right for (let i = 0; i < scores.length - 1; i++) { if (scores[i] < scores[i + 1]) { // Swap if current element < next element [scores[i], scores[i + 1]] = [scores[i + 1], scores[i]]; } } console.log(scores); // Output: [50, 40, 30, 20] (50>40, others adjusted)
Key Notes:
Destructuring is concise but avoid using it on sparse arrays (holes).
Always validate indices to prevent runtime errors.
For large arrays, temporary variables are performance-optimal.
Non-mutating approach: Create a new array if you need immutability:
const newArr = [...arr]; // Copy array [newArr[i], newArr[j]] = [newArr[j], newArr[i]]; // Swap in copy
Practice Exercise:
Swap the first and last elements of any array without knowing its length:
// Solution: let arr = [10, 20, 30, 40]; [arr[0], arr[arr.length - 1]] = [arr[arr.length - 1], arr[0]]; console.log(arr); // [40, 20, 30, 10]
No comments:
Post a Comment