In this tutorial, we will be using a function to swap array elements in JavaScript/jQuery. We will implement the same objective, using an Array.prototype.
Hence, let's start with the code.
Method 1
Check the code, mentioned below. Here, I have used jQuery version 3.1.0. Inside the $(document).ready() section, we have declared an array and a Swap() function to swap the array elements. We are passing the actual array and the indexes to this function.
- <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
- <script type="text/javascript">
- $(document).ready(function(){
- var myArray = [18,3,90,25,2,27,36, 22, 4]; //Declare the array
- var testString = ''; // declare a temporary variable to store the sorted array values.
- //Declare the function to swap the array elements using a third variable.
- //Here we are passing the array indexes as well as the array itself
- function Swap(arr,a, b){
- var temp;
- temp = arr[a];
- arr[a] = arr[b];
- arr[b] = temp;
- }
- //Declare the function to sort the array
- function Sort(array){
- for(var j = 0; j< array.length-1; j++){
- for(var k = 1; k< array.length; k++){
- if(array[k] < array[k - 1]){
- Swap(array,k,k-1) //call the Swap function here
- }
- }
- }
- }
- //Call the Sort Function with the array declared above
- Sort(myArray);
- //Loop through the sorted array elements after swapping
- for(var i = 0; i < myArray.length; i++){
- testString += ", " + myArray[i];
- }
- alert(testString.substring(2)); // Display the sorted array after swapping
- });
- </script>
Method 2
In this method, we will implement the Swap() function with the Array.prototype builtin. Check with the code, mentioned below. I have added Swap() function to Array.prototype.
P.S
This method should be avoided while working with multiple JS library, as it may create confusion.
- <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
- <script type="text/javascript">
- $(document).ready(function(){
- var myArray = [18,3,90,25,2,27,36, 22, 4];
- var testString = '';
- //Declare the Swap function with Array.prototype. We are only passing the indexes here.
- Array.prototype.Swap = function (x,y) {
- var b = this[x];
- this[x] = this[y];
- this[y] = b;
- return this; // return the current array instance.
- }
- //Declare the sort function
- function Sort(array){
- for(var j = 0; j< array.length-1; j++){
- for(var k = 1; k< array.length; k++){
- if(array[k] < array[k - 1]){
- array.Swap(k,k-1) // Call the Swap() function like this.
- }
- }
- }
- }
- //call the Sort() function
- Sort(myArray);
- for(var i = 0; i < myArray.length; i++){
- testString += ", " + myArray[i];
- }
- alert(testString.substring(2)); // display the sorted array.
- });
- </script>

Join the conversation! Your thoughts help the community grow.