Skip to content

Sorting array in JavaScript using for loop | Example code

  • by

You have to use multiple (nested) loops to Sort arrays in JavaScript using for loop. there are more efficient ways but if you want to use the for loop the check below code.

Sorting array in JavaScript using for loop

Simple example code Sort an array containing numbers using For loop.

<!DOCTYPE html>
<html>
<body>
  <script>
   var input = [2,3,8,1,4,5,9,7,6];

   var output = [];
   var inserted;

   for (var i = 0, ii = input.length ; i < ii ; i++){
    inserted = false;
    for (var j = 0, jj = output.length ; j < jj ; j++){
      if (input[i] < output[j]){
        inserted = true;
        output.splice(j, 0, input[i]);
        break;
      }
    }
    
    if (!inserted)
      output.push(input[i])
  }

  console.log(output);
</script>
</body>
</html> 

Output:

Sorting array in JavaScript using for loop

If you want to sort the array, you can use sort method:

var sorted = [3, 1, 6, 2].sort(); // sort ascending  
var sorted = [3, 1, 6, 2].sort(function(a, b){
    return b - a;
}); // sort descending 

How to sort an array from a big number to a small number loop in JavaScript?

Answer: Here is the code

function sortArray(array) {
  var temp = 0;
  for (var i = 0; i < array.length; i++) {
    for (var j = i; j < array.length; j++) {
      if (array[j] < array[i]) {
        temp = array[j];
        array[j] = array[i];
        array[i] = temp;
      }
    }
  }
  return array;
}

console.log(sortArray([3,1,2]));

Output: [ 1, 2, 3 ]

Do comment if you have any doubts or suggestions on this JS array sorting topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading