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;
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);
}
}
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' ]
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
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]
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");
If there is a need to swap the first and last elements only:
array.unshift( array.pop() );
[1, 2, 3] => [3, 1, 2] instead of [1, 2, 3] => [3, 2, 1].
with()you can do it in one line:list.with(x,list[y]).with(y,list[x])see my answer with an example!