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];
- var testString = '';
-
-
-
- function Swap(arr,a, b){
- var temp;
- temp = arr[a];
- arr[a] = arr[b];
- arr[b] = temp;
- }
-
-
- 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)
- }
- }
- }
- }
-
-
- Sort(myArray);
-
-
- for(var i = 0; i < myArray.length; i++){
- testString += ", " + myArray[i];
- }
-
- alert(testString.substring(2));
-
- });
- </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 = '';
-
-
- Array.prototype.Swap = function (x,y) {
- var b = this[x];
- this[x] = this[y];
- this[y] = b;
- return this;
- }
-
-
-
- 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)
- }
- }
- }
- }
-
-
- Sort(myArray);
-
- for(var i = 0; i < myArray.length; i++){
- testString += ", " + myArray[i];
- }
-
- alert(testString.substring(2));
-
- });
- </script>
I hope, this will be helpful for the beginners in JavaScript. Please comment and provide the feedback, if you like my post. Thank you for reading.