How to swap two array elements in JavaScript

How to swap 2 elements in an array in JavaScript?

Suppose we have an arrayaIt contains 5 letters.

const a = ['a', 'b', 'c', 'e', 'd']

We want to swap the element at index 4 ('d' in this case) with the element at index 3 ('e' in this case).

We can use a temporary itemtmpStore the value of #4, then replace #3 with #4, and then assign the temporary item to #3:

const tmp = a[4]
a[4] = a[3]
a[3] = tmp

Another option that does not involve declaring temporary variables is to use the following syntax:

const a = ['a', 'b', 'c', 'e', 'd'];

[a[3], a[4]] = [a[4], a[3]]

Now arrayaWill order correctly according to our requirements.

a //[ 'a', 'b', 'c', 'd', 'e' ]

Download mine for freeJavaScript beginner's manual


More js tutorials: