javascriptarrays

Swap array elements in JavaScript


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;

Solution

  • You only need one temporary variable.

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

    Or with ES6 and later:

    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.