xxxxxxxxxx
const edibles = ["food", "fruits"];
let [positionOne, positionTwo] = edibles;
const temp = positionOne;
positionOne = positionTwo;
positionTwo = temp;
console.log(positionOne, positionTwo);
// fruits, food
xxxxxxxxxx
// How to swap two array elements in JavaScript
const arr = ['a', 'b', 'c', 'e', 'd'];
[arr[1], arr[0]] = [arr[0], arr[1]]
console.log(arr);
// Output:
// [ 'b', 'a', 'c', 'e', 'd' ]
xxxxxxxxxx
let a = 1;
let b = 3;
[a, b] = [b, a]; // destructuring assignment, assigning the value of a and b to a new array created with b and a
console.log(a); // 3
console.log(b); // 1
const arr = [1,2,3];
[arr[2], arr[1]] = [arr[1], arr[2]];
console.log(arr); // [1,3,2]
xxxxxxxxxx
// Before ES6
const temp = a[x]; // NOT RECOMMENDED UNLESS COMPLETELY UNAVOIDABLE
a[x] = a[y];
a[y] = temp;
xxxxxxxxxx
var a = [1,2,3,4,5], b=a.length;
for (var i=0; i<b; i++) {
a.unshift(a.splice(1+i,1).shift());
}
a.shift();
//a = [5,4,3,2,1];
xxxxxxxxxx
import java.util.Arrays;
public class swapInArray {
public static void main (String[] args) {
int[] arr = {1,10,100,1000};
swap(arr,1,3);
System.out.println(Arrays.toString(arr));
}
private static void swap (int[] arr, int index1, int index2){
int elem1 = arr[index1];
int elem2 = arr[index2];
arr[index1] = elem1;
arr[index2] = elem2;
}
}