It is possible to sort arrays in ascending/descending order using the for loop JavaScript as well as by using JavaScript Sort Method. Multiple or nested loos are used for sorting arrays using for loops in JavaScript or using while loop. The example sorting an array of number using for loops is given below.
Sorting arrays using for loops in JavaScript in Ascending order
Simple example code Sort an array containing numbers using For loop.
<!DOCTYPE html> <html> <body> <script> var numbers= [2,3,8,1,4,5,9,7,6]; var SortedNumbers= []; var inserted; for (var k = 0, kk = input.length ; k < kk ; k++){ inserted = false; for (var l = 0, ll = output.length ; l < ll ; l++){ if (numbers[k] < SortedNumbers[l]){ inserted = true; output.splice(j, 0, numbers[i]); break; } } if (!inserted) output.push(numbers[k]) } console.log(SortedNumbers); </script> </body> </html>
Sorting arrays using for loops in JavaScript in Descending order
<!DOCTYPE html> <html> <body> <script> var numbers= [2,3,8,1,4,5,9,7,6]; var SortedNumbers= []; var inserted; for (var k = 0, kk = input.length ; k < kk ; k++){ inserted = false; for (var l = 0, ll = output.length ; l < ll ; l++){ if (numbers[k] > SortedNumbers[l]){ inserted = true; output.splice(j, 0, numbers[i]); break; } } if (!inserted) output.push(numbers[k]) } console.log(SortedNumbers); </script> </body> </html>