JavaScript Swap Array Elements

Javascript swap array elements

You only need one temporary variable.

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

Edit hijacking top answer 10 years later with a lot of ES6 adoption under our belts:

Given the array arr = [1,2,3,4], you can swap values in one line now like so:

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

This would produce the array [2,1,3,4]. This is destructuring assignment.

Swap two elements between two arrays in Javascript

You could use array destructuring for swapping elements.

const a = ['a', 'b', 'c', 'd', 'e', 'f'];
const b = ['g', 'h', 'i', 'j', 'k', 'l'];
let idxC = a.indexOf('c'), idxL = b.indexOf('l');
[a[idxC], b[idxL]] = [b[idxL], a[idxC]];
console.log(JSON.stringify(a));
console.log(JSON.stringify(b));

Swapping two items in a javascript array

Just reassign the elements, creating an intermediate variable to save the first one you over-write:

var swapArrayElements = function(arr, indexA, indexB) {
var temp = arr[indexA];
arr[indexA] = arr[indexB];
arr[indexB] = temp;
};
// You would use this like: swapArrayElements(myArray, 3, 7);

If you want to make this easier to use, you can even add this to the builtin Array prototype (as kennebec@ suggests); however, be aware that this is generally a bad pattern to avoid (since this can create issues when multiple different libraries have different ideas of what belongs in the builtin types):

Array.prototype.swap = function(indexA, indexB) {
swapArrayElements(this, indexA, indexB);
};
// You would use this like myArray.swap(3, 7);

Note that this solution is significantly more efficient than the alternative using splice(). (O(1) vs O(n)).

How does this function to swap array elements work?

Starting with the righthand side:

[a[j], a[i]]

This creates a new array with two elements: the element at index j, followed by the element at index i.

On the left hand side it's doing destructuring

[a[i], a[j]] = 

So that's the equivalent of the following:

a[i] = theNewArray[0];
a[j] = theNewArray[1];

Since this is mutating a, those changes can be felt by any references to the array, so data will "see" the changes.

How to swap array element from one position to another using lodash?

If what you want is just to to swap the index locations of two elements of an array, you can implement that yourself pretty quickly using native JavaScript. Here is a solution using modern ES6+ syntax:

const swapArrayLocs = (arr, index1, index2) => {
[arr[index1], arr[index2]] = [arr[index2], arr[index1]]
}

If you've never seen a destructuring assignment like I used above, you can read about it here. It is an especially helpful technique with this kind of problem when you need to swap the value of two variables (or in this case, two array indices).

Just in case you need to support legacy browsers like Internet Explorer, here is an ES5- version that is a little more syntactically verbose:

var swapArrayLocs = function (arr, index1, index2) {
var temp = arr[index1];

arr[index1] = arr[index2];
arr[index2] = temp;
}

You could also use a function declaration (rather than the function expressions above) with either method:

function swapArrayLocs(arr, index1, index2) {
var temp = arr[index1];

arr[index1] = arr[index2];
arr[index2] = temp;
}

All of the above methods for implementing the functionality you're looking for will be used in the same manner - just as with any other function call. You will call the function then pass it the array you want to affect, and the two array indices whose values you want to swap.

const myArray = ["a", "b", "c", "d", "e", "f"];

swapArrayLocs(myArray, 0, 4);

// myArray is now: ["e", "b", "c", "d", "a", "f"]

This will manipulate the array, but the functions I wrote do not return anything. If you wish to change that you could add a return statement to it at the end to pass arr back or possibly an array containing the two elements that were swapped... whatever you need for your particular use case.

Javascript: How can I swap elements of an array of objects (by reference, not index)?

If you have the reference you can safely retrieve the index by Array.indexOf():

a.indexOf(myReference) // returns the index of the reference or -1

Then, with retrieved index, you can proceed as usual.

Like this:

let a = [{ v: 0 }, { v: 1 }, { v: 2 }, { v: 3 }];
const s1 = a[2];const s2 = a[3];console.log(a.indexOf(s1))

Swap two array elements in a functional way

Short and reliable but admittedly hard to read:

const swap = (x, y) => ([...xs]) => xs.length > 1 ? ([xs[x], xs[y]] = [xs[y], xs[x]], xs) : xs;
const xs = [1,2,3,4,5];
const swap12 = swap(1, 2);
console.log( swap12(xs), "exception (one element):", swap12([1]), "exception (empty list):", swap12([]));


Related Topics



Leave a reply



Submit