2

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 questions in a textbook before a class test.

Any pointers would be appreciated!

a = Number(prompt("a:"));
b = Number(prompt("b:"));
c = Number(prompt("c:"));
d = Number(prompt("d:"));
e = Number(prompt("e:"));

// find largest element
var test = [a, b, c, d, e];
var biggest = -Infinity;
var biggest_index = -1; {
    for (i = 0; i < test.length; i++) {
        if (test[i] > biggest) {
            biggest = test[i];
            biggest_index = i;
        }
        else;
    }
    alert("The biggest element is " + biggest + " at index " + biggest_index);
}

// move largest element of array to the last index
test[test.length] = biggest;

// get rid of copy
test[biggest_index] = 0;
alert("Unsorted: " + test);

// shuffle ??
2
  • If your criterion is "least code", then: alert(Math.max.apply(null, array)); is pretty short. But it doesn't use a for loop. :-) Commented Oct 24, 2011 at 7:31
  • Oh, setting the biggest to 0 will not remove it from the array, you need to use Array.prototype.splice() for that, I'll let you look it up in ECMA-262. Commented Oct 24, 2011 at 7:33

6 Answers 6

3

If you want to get the max/min number in an array, why not use Math.max/Math.min?

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Worth noting that not all browsers support passing a function to sort (they are old but still around). Sorting an array will modify the original array, which may not be what the OP wants. An alternative is to copy the array first.
2

Sure it's possible. First you should decide which algorithm you want to sort with. See here for some great visual examples http://www.sorting-algorithms.com/

From your example though, you'll need another for loop. So far you're finding the biggest, you'll need another loop to repeat your logic, but find the second biggest, than third, than 4th. etc.

Comments

0

javascript has a sort function for arrays.

You can do

alert("Sorted: "+ test.sort());

Comments

0

If you're just looking for an efficient way to sort an array, it's best to just use the built-in sort() method.

Using it can be as simple as this :

var unsortedArray = [12, 55, 35, 11, 88, 13, 6];
var sortedArray = unsortedArray.sort();

If you don't want to use the built-in sort() method for some reason (eg. educational purposes), you should do some research on sorting algorithms.

These are some of the most popular sorting algorithms out there :

Comments

0

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:

Sorting Greatest to Least

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 ]

Sorting Least to Greatest

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 ]

Comments

0

this for A to B

function smallTobig(numbers) {

let A_B = []
    for(let i = 0; i < numbers.length; i++) {
     for(let j = i; j < numbers.length; j++) {
        if (numbers[i] > numbers[j]) {
            let temp = numbers[i];
            numbers[i] = numbers[j];
            numbers[j] = temp;
        }
    }
    A_B.push(numbers[i])
}
return A_B
}
console.log(smallTobig([5, 2, 1, 4])); 
console.log(smallTobig([999, 5, 0, 1, 4, 998])); 
console.log(smallTobig([15, 32, 11, 14]));
console.log(smallTobig([5, 4, 3, 2, 1, 0]));
console.log(smallTobig([123, 321, 143, 313]));

this for B to A

function bigTosmall(numbers) {

let B_A = []
    for(let i = 0; i < numbers.length; i++) {
     for(let j = i; j < numbers.length; j++) {
        if (numbers[i] < numbers[j]) {
            let temp = numbers[i];
            numbers[i] = numbers[j];
            numbers[j] = temp;
        }
    }
    B_A.push(numbers[i])
}
return B_A
}
console.log(bigTosmall([5, 2, 1, 4])); 
console.log(bigTosmall([999, 5, 0, 1, 4, 998])); 
console.log(bigTosmall([15, 32, 11, 14]));
console.log(bigTosmall([5, 4, 3, 2, 1, 0]));
console.log(bigTosmall([123, 321, 143, 313]));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.