How to Swap Array Elements in JavaScript

To swap elements in an array in JavaScript, use a temporary variable or array destructuring.

let arr = [1, 2, 3, 4];
let temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;
console.log(arr); // [2, 1, 3, 4]

// OR

[arr[0], arr[1]] = [arr[1], arr[0]];
console.log(arr); // [2, 1, 3, 4]

Swapping elements in an array is a common task in programming. In JavaScript, you can swap elements using various methods. This guide covers different techniques to swap array elements efficiently.

Using a Temporary Variable

The most straightforward way to swap elements is by using a temporary variable.

Example 1: Using a Temporary Variable

let arr = [1, 2, 3, 4];

let temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;

console.log(arr); // [2, 1, 3, 4]

Explanation:

  • let arr = [1, 2, 3, 4]; Initializes the array.
  • let temp = arr[0];
    Stores the value of the first element in a temporary variable.
  • arr[0] = arr[1]; Assigns the value of the second element to the first element.
  • arr[1] = temp;
    Assigns the value of the temporary variable (initially the first element) to the second element.
  • console.log(arr); Logs the array to show the swapped elements.

Using Array Destructuring

Array destructuring provides a concise way to swap elements.

Example 2: Using Array Destructuring

let arr = [1, 2, 3, 4];

[arr[0], arr[1]] = [arr[1], arr[0]];

console.log(arr); // [2, 1, 3, 4]

Explanation:

  • let arr = [1, 2, 3, 4]; Initializes the array.
  • [arr[0], arr[1]] = [arr[1], arr[0]]; Swaps the first and second elements using array destructuring.
  • console.log(arr); Logs the array to show the swapped elements.

Using a Custom Function

Creating a custom function to swap elements can make the code reusable and more readable.

Example 3: Using a Custom Function

function swapElements(arr, index1, index2) {
  let temp = arr[index1];
  arr[index1] = arr[index2];
  arr[index2] = temp;
}

let arr = [1, 2, 3, 4];
swapElements(arr, 0, 1);

console.log(arr); // [2, 1, 3, 4]

Explanation:

  • function swapElements(arr, index1, index2) { ... } Defines a function to swap elements at given indices.
  • let arr = [1, 2, 3, 4]; Initializes the array.
  • swapElements(arr, 0, 1); Calls the function to swap the first and second elements.
  • console.log(arr); Logs the array to show the swapped elements.

Using the ES6 Swap Function

You can also use a swap function with ES6 features to swap elements in an array.

Example 4: Using the ES6 Swap Function

const swap = (arr, idx1, idx2) => {
  [arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
};

let arr = [1, 2, 3, 4];
swap(arr, 0, 1);

console.log(arr); // [2, 1, 3, 4]

Explanation:

  • const swap = (arr, idx1, idx2) => { ... } Defines an arrow function to swap elements at given indices using array destructuring.
  • let arr = [1, 2, 3, 4]; Initializes the array.
  • swap(arr, 0, 1); Calls the function to swap the first and second elements.
  • console.log(arr); Logs the array to show the swapped elements.

Handling Edge Cases

Ensure to handle edge cases such as invalid indices or non-array inputs.

Example 5: Handling Edge Cases

function safeSwapElements(arr, index1, index2) {
  if (!Array.isArray(arr) || index1 < 0 || index2 < 0 || index1 >= arr.length || index2 >= arr.length) {
    return 'Invalid input';
  }
  
  let temp = arr[index1];
  arr[index1] = arr[index2];
  arr[index2] = temp;
}

let arr = [1, 2, 3, 4];
console.log(safeSwapElements(arr, 0, 1)); // undefined, arr is now [2, 1, 3, 4]

console.log(safeSwapElements(arr, -1, 1)); // 'Invalid input'

Explanation:

  • function safeSwapElements(arr, index1, index2) { ... } Defines a function to swap elements at given indices, with input validation.
  • if (!Array.isArray(arr) || index1 < 0 || index2 < 0 || index1 >= arr.length || index2 >= arr.length) { return 'Invalid input'; } Checks for invalid input such as non-array or out-of-bound indices.
  • let temp = arr[index1]; Stores the value of the first element in a temporary variable.
  • arr[index1] = arr[index2]; Assigns the value of the second element to the first element.
  • arr[index2] = temp; Assigns the value of the temporary variable (initially the first element) to the second element.
  • let arr = [1, 2, 3, 4]; Initializes the array.
  • console.log(safeSwapElements(arr, 0, 1)); Logs the result of the swap operation.
  • console.log(safeSwapElements(arr, -1, 1)); Logs the validation message for invalid input.

Conclusion

Swapping elements in an array can be achieved through various methods in JavaScript. Whether using a temporary variable, array destructuring, a custom function, or handling edge cases, JavaScript provides robust tools to manage array manipulation. Understanding these techniques allows you to choose the most appropriate method for your specific needs, ensuring your code is efficient and effective.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top