# JavaScript交换数组元素

2020/10/11 16:41 · javascript ·  · 0评论

``````var a = list[x], b = list[y];
list[y] = a;
list[x] = b;
``````

``````var b = list[y];
list[y] = list[x];
list[x] = b;
``````

10年后，我们大量采用了ES6，从而编辑劫持性最高答案：

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

``````var A = [1, 2, 3, 4, 5, 6, 7, 8, 9], x= 0, y= 1;
A[x] = A.splice(y, 1, A[x])[0];
``````

`[0]`是在表达的端部必要`Array.splice()`的阵列的回报，并且在这种情况下，我们所需要的返回数组中的单个元件。

``````var b = list[y];
list[y] = list[x];
list[x] = b;
``````

``````var b = list[y];
``````

``````Array.prototype.swap = function (x,y) {
var b = this[x];
this[x] = this[y];
this[y] = b;
return this;
}
``````

``````list.swap( x, y )
``````

``````[ list[x], list[y] ] = [ list[y], list[x] ];
``````

``````var tmp = list[x];
list[x] = list[y];
list[y] = tmp;
``````

``````list[x] = [list[y],list[y]=list[x]][0]
``````

``````list = [1,2,3,4,5]
list[1] = [list[3],list[3]=list[1]][0]
//list is now [1,4,3,2,5]
``````

``````var a=1,b=5;
a = [b,b=a][0]
``````

``````let a = 1, b = 2;
// a: 1, b: 2
[a, b] = [b, a];
// a: 2, b: 1
``````

``````list[x] = list[x] ^ list[y];
list[y] = list[y] ^ list[x];
list[x] = list[x] ^ list[y];
``````

``````list[x] = list[x] + list[y];
list[y] = list[x] - list[y];
list[x] = list[x] - list[y];
``````

``````array.splice(IndexToSwap,2,array[IndexToSwap+1],array[IndexToSwap]);
``````
``````var a = 5, b = 9;
b = (a += b -= a) - b;
``````
``````var arr = [1, 2, 3, 4]
[arr[index1], arr[index2]] = [arr[index2], arr[index1]]
``````

``````[src order elements] => [dest order elements]
``````

``````function swap(arr, from, to) {
arr.splice(from, 1, arr.splice(to, 1, arr[from])[0]);
}

var letters = ["a", "b", "c", "d", "e", "f"];

swap(letters, 1, 4);

console.log(letters); // ["a", "e", "c", "d", "b", "f"]``````

``````var swap = function (x){return x};
b = swap(a, a=b);
c = swap(a, a=b, b=c);
``````

``````var swap = function (x){return x};
list[y]  = swap(list[x], list[x]=list[y]);
``````

### 对于两个或多个元素（固定数量）

``````[list[y], list[x]] = [list[x], list[y]];
``````

`list.length = x + y + 1`

### 对于可变数量的元素

``````function multiswap(arr,i0,i1) {/* argument immutable if string */
if (arr.split) return multiswap(arr.split(""), i0, i1).join("");
var diff = [];
for (let i in i0) diff[i0[i]] = arr[i1[i]];
return Object.assign(arr,diff);
}

Example:
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var [x,y,z] = [14,6,15];
var output = document.getElementsByTagName("code");
output[0].innerHTML = alphabet;
output[1].innerHTML = multiswap(alphabet, [0,25], [25,0]);
output[2].innerHTML = multiswap(alphabet, [0,25,z,1,y,x], [25,0,x,y,z,3]);``````
``````<table>
<tr><td>Input:</td>                        <td><code></code></td></tr>
<tr><td>Swap two elements:</td>            <td><code></code></td></tr>
<tr><td>Swap multiple elements:&nbsp;</td> <td><code></code></td></tr>
</table>``````

``````var a = 1;
var b = 2;
[a,b] = [b,a];
``````

（ES6方式）

`let newList = Object.assign([], list, {[x]: list[y], [y]: list[x]})`

（使用发布问题时2009年不可用的语言功能！）

``````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];
``````

``````arr.slice(0,i1).concat(arr[i2],arr.slice(i1+1,i2),arr[i1],arr.slice(i2+1))
``````

``````Array.prototype.swapItems = function(a, b){
if(  !(a in this) || !(b in this) )
return this;
this[a] = this.splice(b, 1, this[a])[0];
return this;
}
``````

``````var swapArrayElements = function (a, x, y) {
if (a.length === 1) return a;
a.splice(y, 1, a.splice(x, 1, a[y])[0]);
return a;
};

swapArrayElements([1, 2, 3, 4, 5], 1, 3); //=> [ 1, 4, 3, 2, 5 ]
``````

Typescript解决方案，可克隆数组而不是对现有数组进行突变

``````export function swapItemsInArray<T>(items: T[], indexA: number, indexB: number): T[] {
const itemA = items[indexA];

const clone = [...items];

clone[indexA] = clone[indexB];
clone[indexB] = itemA;

return clone;
}
``````

``````var foo = [ 0, 1, 2, 3, 4, 5, 6 ];
``````

``````foo.splice( a, 1, foo.splice(b,1,foo[a])[0] );
``````

``````foo.splice( 3, 1, foo.splice(5,1,foo[3])[0] );
``````

``````foo.splice( 5, 1, foo.splice(3,1,foo[5])[0] );
``````

``````console.log( foo );
// => [ 0, 1, 2, 5, 4, 3, 6 ]
``````

#splicehatersarepunks :)

`[a.pop(), ...a.slice(1), a.shift()]`

``````Array.prototype.swap = function(a, b) {
var temp = this[a];
this[a] = this[b];
this[b] = temp;
};
``````

``````var myArray = [0,1,2,3,4...];
myArray.swap(4,1);
``````
``````var arr = [1, 2];
arr.splice(0, 2, arr[1], arr[0]);
console.log(arr); //[2, 1]``````
``````function moveElement(array, sourceIndex, destinationIndex) {
return array.map(a => a.id === sourceIndex ? array.find(a => a.id === destinationIndex): a.id === destinationIndex ? array.find(a => a.id === sourceIndex) : a )
}
let arr = [
{id: "1",title: "abc1"},
{id: "2",title: "abc2"},
{id: "3",title: "abc3"},
{id: "4",title: "abc4"}];

moveElement(arr, "2","4");
``````

# 流

``````let swap= (arr,i,j)=> arr.map((e,k)=> k-i ? (k-j ? e : arr[i]) : arr[j]);
``````

``````var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// swap index 0 and 2
arr[arr.length] = arr[0];   // copy idx1 to the end of the array
arr[0] = arr[2];            // copy idx2 to idx1
arr[2] = arr[arr.length-1]; // copy idx1 to idx2
arr.length--;               // remove idx1 (was added to the end of the array)

console.log( arr ); // -> [3, 2, 1, 4, 5, 6, 7, 8, 9]``````

``````\$(document).ready(function () {
var pair = [];
var destinationarray = ['AAA','BBB','CCC'];

var cityItems = getCityList(destinationarray);
for (var i = 0; i < cityItems.length; i++) {
pair = [];
var ending_point = "";
for (var j = 0; j < cityItems[i].length; j++) {
pair.push(cityItems[i][j]);
}
console.log(pair)
}

});
function getCityList(inputArray) {
var Util = function () {
};

Util.getPermuts = function (array, start, output) {
if (start >= array.length) {
var arr = array.slice(0);
output.push(arr);
} else {
var i;

for (i = start; i < array.length; ++i) {
Util.swap(array, start, i);
Util.getPermuts(array, start + 1, output);
Util.swap(array, start, i);
}
}
}

Util.getAllPossiblePermuts = function (array, output) {
Util.getPermuts(array, 0, output);
}

Util.swap = function (array, from, to) {
var tmp = array[from];
array[from] = array[to];
array[to] = tmp;
}
var output = [];
Util.getAllPossiblePermuts(inputArray, output);
return output;
}``````
``<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>``

``````const a = ["a", "b", "c", "d", "e"];
const b = [5, 4, 3, 2, 1];
``````

``````const [a0] = a;
a[0] = b[0];
b[0] = a0;
``````

``````a; //[5, "b", "c", "d", "e"]
b; //["a", 4, 3, 2, 1]
``````