Table of Contents
Arrays are a useful data structure for storing a collection of data in a single variable.
Sometimes you want to be able to switch around the positions of two elements in an array.
In this post, we'll learn how you can swap the position of two elements in an array in JavaScript.
How to swap two elements in an array
Let's start off with an example array:
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
This is a basic 5-element array. Now let's try and swap the 2nd and 4th elements in the array.
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
const temp = array[1];
array[1] = array[3];
array[3] = temp;
console.log(array);
BASH[1, 4, 3, 2, 5]
In this case, we are using a temporary variable to store the value of the element we want to swap.
Then we perform the swap, and place the temporary variable back into the array.
Conclusion
In this post, we learned how to swap the positions of two elements of an array.
Simply use a temporary variable to hold the value of one of the two elements, perform the swap, then restore the value in the other slot.
Thanks for reading and happy coding!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- Getting Started with Deno
- How to deploy an Express app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase