Sling Academy
Home/JavaScript/JavaScript: 4 Ways to Swap Elements in an Array

JavaScript: 4 Ways to Swap Elements in an Array

Last updated: March 09, 2023

This concise example-based article will walk you through 4 different approaches to swapping elements in a given array in JavaScript.

Using the array destructing syntax

Array destructuring is a JavaScript expression that allows us to extract data from arrays or iterable objects into separate variables.

In the context of swapping elements in an array, we can use array destructuring to assign the values of the two elements to be swapped to separate variables and then assign them back to their new positions in the array.

In the example below, we will swap the position of the first Element (with Index 0) and the fourth element (with Index 3):

const array = ['A', 'B', 'C', 'D', 'E'];
[array[0], array[3]] = [array[3], array[0]];
console.log(array);

Output:

[ 'D', 'B', 'C', 'A', 'E' ]

As you can see, we only need a single line of code to do the swapping job.

Using a temporary variable

This is a classic technique in programming, and it is quite understandable.

Example:

let array = ['A', 'B', 'C', 'D', 'E'];
let temp = array[1];
array[1] = array[3];
array[3] = temp;
console.log(array);

Output:

[ 'A', 'D', 'C', 'B', 'E' ]

Using the Subtraction Method

The subtraction method involves subtracting one element from the other to swap their values. This method only works if the two elements being swapped are numeric values.

Example:

const array = [1000, 2000, 3000, 4000];

// swap 2000 and 4000
array[1] = array[1] - array[3];
array[3] = array[1] + array[3];
array[1] = array[3] - array[1];

console.log(array);

Output:

[ 1000, 4000, 3000, 2000 ]

If you are a person who likes the beauty of mathematics, this method will suit you.

Using the splice() method

Another possible solution is to use the splice() method, which can remove and insert elements in an array.

Example:

let arr = ['sling', 'academy', 'dot com']; 

// swap first and third elements 
arr[0] = arr.splice(2, 1, arr[0])[0]; 

console.log(arr); 

Output:

[ 'dot com', 'academy', 'sling' ]

Closing Thoughts

All mentioned approaches in this article are decent and concise. However, most developers prefer and use one of the first two methods. How about you? Let us know your opinion by leaving a comment.

Next Article: JavaScript: Pass an Array to a Function as Multiple Arguments

Previous Article: JavaScript: 4 Ways to Flatten an Array

Series: Working with Arrays in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration