356

Is there a simpler way to swap two elements in an array?

var a = list[x], b = list[y];
list[y] = a;
list[x] = b;
1
  • ES2023 Array Method with() you can do it in one line: list.with(x,list[y]).with(y,list[x]) see my answer with an example! Commented Jun 11, 2023 at 11:04

37 Answers 37

1
2
0

In place swap:

// Array methods
function swapInArray(arr, i1, i2){
    let t = arr[i1];
    arr[i1] = arr[i2];
    arr[i2] = t;
}

function moveBefore(arr, el){
    let ind = arr.indexOf(el);
    if(ind !== -1 && ind !== 0){
        swapInArray(arr, ind, ind - 1);
    }
}

function moveAfter(arr, el){
    let ind = arr.indexOf(el);
    if(ind !== -1 && ind !== arr.length - 1){
        swapInArray(arr, ind + 1, ind);
    }
}

// DOM methods
function swapInDom(parentNode, i1, i2){
    parentNode.insertBefore(parentNode.children[i1], parentNode.children[i2]);
}

function getDomIndex(el){
    for (let ii = 0; ii < el.parentNode.children.length; ii++){
        if(el.parentNode.children[ii] === el){
            return ii;
        }
    }
}

function moveForward(el){
    let ind = getDomIndex(el);
    if(ind !== -1 && ind !== 0){
        swapInDom(el.parentNode, ind, ind - 1);
    }
}

function moveBackward(el){
    let ind = getDomIndex(el);
    if(ind !== -1 && ind !== el.parentNode.children.length - 1){
        swapInDom(el.parentNode, ind + 1, ind);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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

function swap (arr, from, to) {
    let temp = arr[from];
    arr.splice(from, 1, arr[to]);
    arr.splice(to, 1, temp);
}

swap(letters, 1, 4)
console.log(letters); // output [ 'a', 'e', 'c', 'd', 'b', 'f' ]

1 Comment

Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.
0

Maybe is useless after 30 answer. This is a way to swap last two items of an array. Is not exactly the answer of your question but a solution I've just found for a specific case of needed swap.

const prev = yourArray.pop(); // remove last
yourArray.push(article); // add one
yourArray.push(prev); // add removed one

Comments

-1

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]

Comments

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

1 Comment

Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.
-2

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]

Comments

-3

If there is a need to swap the first and last elements only:

array.unshift( array.pop() );

1 Comment

This code is flawed. It takes the last element of the array then puts it at the beginning, that isn't swapping. This code does this: [1, 2, 3] => [3, 1, 2] instead of [1, 2, 3] => [3, 2, 1].
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.