One of the simplest methods is to use a temporary variable that holds one of the elements, allowing the values to be exchanged. This technique ensures that the values are not lost during the swapping process.
Here's an example of a function that takes in the array and the indices of the elements to be swapped:
const swapArrayElements = (arr, index1, index2) => {
if (index1 < 0 || index1 >= arr.length || index2 < 0 || index2 >= arr.length) {
return "Invalid index provided.";
}
let temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
return arr;
};
// Example usage
let array = [1, 2, 3, 4, 5];
console.log("Swapping elements at index 1 and 3:", swapArrayElements(array, 1, 3));
// Swapping elements at index 1 and 3: [1, 4, 3, 2, 5]
Another method is to use array destructuring to swap the elements.
let array = [1, 2, 3, 4, 5];
// Swapping elements at index 1 and 3
[array[1], array[3]] = [array[3], array[1]];
console.log(array); // [1, 4, 3, 2, 5]