Is it possible to sort arrays in ascending/descending order using the for loop JavaScript?
I\'ve been learning JS going through a few practice quest
I was actually working on manually sorting javascript arrays with for loops today. While the code below does assume you're feeding it arrays (e.g, does not check for types), here was a solution I was able to get using for
loops only, no built-in sorting methods and no new array creation:
function sortGreatest(arr) {
// manually sort array from largest to smallest:
// loop forwards through array:
for (let i = 0; i < arr.length; i++) {
// loop through the array, moving forwards:
// note in loop below we set `j = i` so we move on after finding greatest value:
for (let j = i; j < arr.length; j++) {
if (arr[i] < arr[j]) {
let temp = arr[i]; // store original value for swapping
arr[i] = arr[j]; // set original value position to greater value
arr[j] = temp; // set greater value position to original value
};
};
};
return arr;
};
console.log(sortGreatest([10,9,1000,12,-11,3]));
// => [ 1000, 12, 10, 9, 3, -11 ]
function sortLeast(arr) {
// manually sort array from smallest to largest:
// loop through array backwards:
for (let i = arr.length-1; i >= 0; i--) {
// loop again through the array, moving backwards:
for (let j = i; j >= 0; j--) {
if (arr[i] < arr[j]) {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
};
};
};
return arr;
};
console.log(sortLeast([10,9,1000,12,-11,3]));
// => [ -11, 3, 9, 10, 12, 1000 ]