Swap Two Array Elements in JavaScript

Published on August 11, 2020 28 sec read

Today we are going to learn how to swap two array elements in JavaScript. Let’s have a look:

Table of Contents

  1. Take an Array
  2. Way 1
  3. Way 2

Take an Array

Suppose, we have a array numbers that contains 5 numbers:

const numbers = [1, 2, 5, 4, 3];

We want to swap index two [5] with index four [2]. We can do it in wo ways.

Way 1

This is the easiest way to swap elements:

const numbers = [1, 2, 5, 4, 3];

[numbers[2], numbers[4]] = [numbers[4], numbers[2]];

console.log(numbers);

We don’t need to take any temp array to do this.

Way 2

We can swap in another way. In this way, we need to take a temp array. Let’s see the example:

const numbers = [1, 2, 5, 4, 3];

const temp = numbers[2];
numbers[2] = numbers[4];
numbers[4] = temp;

console.log(numbers);

In the console, we will see the output like:

[1, 2, 3, 4, 5]
That’s it. Thanks for reading. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

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