Javascript swap array elements 

How do I swap two elements in an array in JavaScript? Suppose we have an array that contains 5 letters. We want to swap the element with index 4 (in this case “d”) with the element with index 3 (in this case “e”). We can use a temporary itemtmp to keep the value of #…

How do I swap two elements in an array in JavaScript?

Suppose we have an array that contains 5 letters.

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


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

We can use a temporary itemtmp to keep the value of # 4, we put # 3 instead of # 4 and assign a temporary item # 3:

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


Another option, not related to the declaration of a temporary variable, is to use this syntax

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

The arrays will now be correctly ordered as we want them to be.

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

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *