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>

Join the conversation! Your thoughts help the community grow.