This page looks best with JavaScript enabled

How to Swap Two Array Element in Javascript

 · ☕ 2 min read · 👽 john hashim

working with javascript array swap it a way to order your array items in the oder that you want your data to be consumed or display .. the snippets bellow may help you archive that.

quick way

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let days = ["Sunday","Monday","Friday","Wednesday","Thursday","Tuesday","Saturday"];

let temp = days[2];
days[2] = days[5];
days[5] = temp;

console.log(days) 
//


1
2
3
4
5
const days = ["Sunday","Monday","Friday","Wednesday","Thursday","Tuesday","Saturday"];

[days[3], days[4]] = [days[4], days[3]]

//

swap function

if it something that will be done regulary its better to create a function and reuse it ..

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const days = ["Sunday","Monday","Friday","Wednesday","Thursday","Tuesday","Saturday"];

function swap(input, index1, index2) {
    let temp = input[index_A];

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

swap(days, 2, 5);
//

extentend function

Now, you may find that using a function to do this a bit weird as well. If you believe that a swap method needs to exist and be available for all arrays in your code, then you can actually extend the Array type with your own swap method

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const days = ["Sunday","Monday","Friday","Wednesday","Thursday","Tuesday","Saturday"];

Array.prototype.swap = function(index1, index2) {
    let input = this;

    let temp = input[index1];
    input[index1] = input[index2];
    input[index2] = temp;
}

days.swap(2, 5);
//

To use this approach, just call the swap method directly from yourdaysarray object as shown. The two index positions you pass in will determine which two items will have their contents swapped.

Share on

john hashim
WRITTEN BY
john hashim
Web Developer