Swap Two Array Elements in JavaScript
Today we are going to learn how to swap two array elements in JavaScript. Let’s have a look:
Table of Contents
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. ?Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.