We can swap values in an array in JavaScript easily by making use of a temporary variable. The easiest way to show how this is done is with an example.

var someArray = [value1,value2];
var temp = someArray[0];
someArray[0] = someArray[1];
someArray[1] = temp;

Lets show a really simple example using this code:

var someArray = [3,4];
var temp = someArray[0];
someArray[0] = someArray[1];
someArray[1] = temp;

console.log(someArray);

#Output:
[4,3]

When working with variables in JavaScript, being able to change the values of variables easily is important.

One such change is swapping the values between two variables.

We can easily swap values in an Array using JavaScript. To swap values you can use a temporary variable.

Below is our code again of how to swap the values in an Array using JavaScript.

var someArray = [value1,value2];
var temp = someArray[0];
someArray[0] = someArray[1];
someArray[1] = temp;

Swap Any Values in an Array in JavaScript

In this example, we will swap any two values in an array. Here is our function that will let you swap any two values of an array. We simply need to give the function the array, the first position of the element to be swapped, and the second position of the element we want to swap it with.

function swapValues(arr,position1,position2){
  var temp = arr[position1];
  arr[position1] = someArray[position2];
  arr[position2] = temp;
};

Let’s see a simple example with this code, swapping the element in the first spot of the array, with the element in the second spot of the array:

function swapValues(arr,position1,position2){
  var temp = arr[position1];
  arr[position1] = someArray[position2];
  arr[position2] = temp;
};

var someArray = ["red","orange","yellow","green","blue","indigo","violet"];
swapValues(someArray,0,1);
console.log(someArray);

#Output:
['orange', 'red', 'yellow', 'green', 'blue', 'indigo', 'violet']

And one more example, swapping the element in the fourth spot of the array, with the element in the seventh spot of the array.

function swapValues(arr,position1,position2){
  var temp = arr[position1];
  arr[position1] = someArray[position2];
  arr[position2] = temp;
};

var someArray = ["red","orange","yellow","green","blue","indigo","violet"];
swapValues(someArray,3,6);
console.log(someArray);

#Output:
['red', 'orange', 'yellow', 'violet', 'blue', 'indigo', 'green']

Hopefully this article has been helpful for you to learn how to swap values in an array with JavaScript.

Categorized in:

JavaScript,

Last Update: March 22, 2024