IT

자바 스크립트 스왑 배열 요소

lottoking 2020. 5. 14. 08:28
반응형

자바 스크립트 스왑 배열 요소


배열에서 두 요소를 바꾸는 더 간단한 방법이 있습니까?

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 = [1,2,3,4]과 같이 한 줄로 값을 바꿀 수 있습니다.

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

이것은 배열을 생성합니다 [2,1,3,4]. 이것은 할당을 파괴하고 있습니다.


기본 자바 스크립트를 사용하여 단일 표현식을 원하면 스플 라이스 연산의 반환 값에 제거 된 요소가 포함되어 있음을 기억하십시오.

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

편집하다:

[0]같은 식의 끝 부분에 필요한 Array.splice()반환 배열,이 상황에서 우리는 반환 된 배열의 단일 요소를 필요로한다.


이것은 괜찮아 보인다 ....

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

Howerver 사용

var b = list[y];

수단 B의 변수는 범위의 나머지 존재하는 것으로 될 것이다. 이로 인해 메모리 누수가 발생할 수 있습니다. 가능하지는 않지만 피하는 것이 좋습니다.

이것을 Array.prototype.swap에 넣는 것이 좋습니다.

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

다음과 같이 호출 할 수 있습니다.

list.swap( x, y )

이것은 메모리 누수DRY를 피하는 깔끔한 접근 방법 입니다.


Metafilter의 무작위 사용자에 따르면 "최신 버전의 Javascript를 사용하면 훨씬 더 깔끔하게 스왑을 수행 할 수 있습니다."

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

빠른 테스트 결과이 Pythonic 코드 는 현재 "Google Apps Script"( ". gs")에서 사용되는 JavaScript 버전에서 훌륭하게 작동합니다. 아아, 추가 테스트에 따르면이 코드는 "Uncaught ReferenceError : Assignment in invalid left-side side in assignment"를 보여줍니다. 모든 버전의 JavaScript ( ". js")에서 Chrome 버전 24.0.1312.57m이 사용됩니다.


음, 값을 모두 버퍼링 할 필요는 없습니다 .

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]

숫자 값을 사용하면 비트 xor를 사용하여 임시 변수를 피할 수 있습니다

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

또는 산술 합계 (x + y가 데이터 유형의 최대 값보다 작은 경우에만 작동 함)

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

질문이있을 때 존재하지 않았지만 ES2015는 배열 파괴를 도입하여 다음과 같이 작성할 수 있습니다.

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

http://www.greywyvern.com/?post=265 에서 다이제스트

var a = 5, b = 9;    
b = (a += b -= a) - b;    
alert([a, b]); // alerts "9, 5"

배열의 두 연속 요소를 바꾸려면

array.splice(IndexToSwap,2,array[IndexToSwap+1],array[IndexToSwap]);

Destructuring_assignment는 어떻 습니까

var arr = [1, 2, 3, 4]
[arr[index1], arr[index2]] = [arr[index2], arr[index1]]

이는 또한 확장 될 수 있습니다

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

다음과 같은 간단한 ID 함수를 사용하여 여러 유형의 객체 또는 리터럴을 다양한 유형으로 바꿀 수 있습니다.

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

추가 인수가 선언되거나 사용되지 않더라도 추가 인수를 허용하므로 JavaScript에서 작동합니다. 할당 a=b후 등 a은 함수에 전달됩니다.


세 번째 변수를 정의 할 필요없이 이러한 솔루션을 고려하십시오.

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"]

참고 : 배열 길이와 같은 추가 검사를 추가 할 수 있습니다. 이 솔루션은 변경 가능 하므로 swap함수는 새로운 배열을 반환 할 필요가 없으며 전달 된 배열에 대한 돌연변이 만 수행합니다.


둘 이상의 요소 (고정 번호)

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

임시 변수가 필요하지 않습니다!

나는 단순히 전화하는 것에 대해 생각하고 있었다 list.reverse().
그러나 그때만 스왑으로 작동한다는 것을 깨달았습니다 list.length = x + y + 1.

가변 개수의 요소

Mapmap을 포함 하여이 효과에 대한 다양한 현대 Javascript 구성을 살펴 보았지만 슬프게도이 구식 루프 기반 구성보다 더 컴팩트하거나 빠른 코드는 없었습니다.

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 방식)


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

Here's a one-liner that doesn't mutate list:

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

(Uses language features not available in 2009 when the question was posted!)


Here's a compact version swaps value at i1 with i2 in arr

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

Here is a variation that first checks if the index exists in the array:

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;
}

It currently will just return this if the index does not exist, but you could easily modify behavior on fail


Just for the fun of it, another way without using any extra variable would be:

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]


For the sake of brevity, here's the ugly one-liner version that's only slightly less ugly than all that concat and slicing above. The accepted answer is truly the way to go and way more readable.

Given:

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

if you want to swap the values of two indices (a and b); then this would do it:

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

For example, if you want to swap the 3 and 5, you could do it this way:

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

or

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

Both yield the same result:

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

#splicehatersarepunks:)


If you don't want to use temp variable in ES5, this is one way to swap array elements.

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 ]

try this function...

$(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]);
            }
            alert(pair);
            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>


Swap the first and last element in an array without temporary variable or ES6 swap method [a, b] = [b, a]

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


var arr = [1, 2];
arr.splice(0, 2, arr[1], arr[0]);
console.log(arr); //[2, 1]


Using ES6 it's possible to do it like this...

Imagine you have these 2 arrays...

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

and you want to swap the first values:

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

and value:

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

If need swap first and last elements only:

array.unshift( array.pop() );

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

Usage:

var myArray = [0,1,2,3,4...];
myArray.swap(4,1);

참고URL : https://stackoverflow.com/questions/872310/javascript-swap-array-elements

반응형