Sorting arrays using for loop in Javascript












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 ??









share|improve this question























  • If your criterion is "least code", then: alert(Math.max.apply(null, array)); is pretty short. But it doesn't use a for loop. :-)

    – RobG
    Oct 24 '11 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.

    – RobG
    Oct 24 '11 at 7:33
















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 ??









share|improve this question























  • If your criterion is "least code", then: alert(Math.max.apply(null, array)); is pretty short. But it doesn't use a for loop. :-)

    – RobG
    Oct 24 '11 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.

    – RobG
    Oct 24 '11 at 7:33














2












2








2


1






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 ??









share|improve this question














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 ??






javascript






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Oct 24 '11 at 3:09









methuselahmethuselah

4,98434105188




4,98434105188













  • If your criterion is "least code", then: alert(Math.max.apply(null, array)); is pretty short. But it doesn't use a for loop. :-)

    – RobG
    Oct 24 '11 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.

    – RobG
    Oct 24 '11 at 7:33



















  • If your criterion is "least code", then: alert(Math.max.apply(null, array)); is pretty short. But it doesn't use a for loop. :-)

    – RobG
    Oct 24 '11 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.

    – RobG
    Oct 24 '11 at 7:33

















If your criterion is "least code", then: alert(Math.max.apply(null, array)); is pretty short. But it doesn't use a for loop. :-)

– RobG
Oct 24 '11 at 7:31





If your criterion is "least code", then: alert(Math.max.apply(null, array)); is pretty short. But it doesn't use a for loop. :-)

– RobG
Oct 24 '11 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.

– RobG
Oct 24 '11 at 7:33





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.

– RobG
Oct 24 '11 at 7:33












6 Answers
6






active

oldest

votes


















2














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





share|improve this answer
























  • 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.

    – RobG
    Oct 24 '11 at 7:28



















1














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.






share|improve this answer































    0














    javascript has a sort function for arrays.



    You can do



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





    share|improve this answer































      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 :




      • Simple sorts :


        • Insertion sort

        • Selection sort



      • Efficient sorts :


        • Merge sort

        • Heapsort

        • Quicksort



      • Bubble sort and variants :



        • Bubble sort

        • Shellsort

        • Comb sort



      • Distribution sort


        • Counting sort

        • Bucket sort

        • Radix sort








      share|improve this answer































        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 ]





        share|improve this answer































          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]));





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7870961%2fsorting-arrays-using-for-loop-in-javascript%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            6 Answers
            6






            active

            oldest

            votes








            6 Answers
            6






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            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





            share|improve this answer
























            • 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.

              – RobG
              Oct 24 '11 at 7:28
















            2














            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





            share|improve this answer
























            • 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.

              – RobG
              Oct 24 '11 at 7:28














            2












            2








            2







            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





            share|improve this answer













            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






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Oct 24 '11 at 3:12









            wong2wong2

            14k3199147




            14k3199147













            • 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.

              – RobG
              Oct 24 '11 at 7:28



















            • 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.

              – RobG
              Oct 24 '11 at 7:28

















            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.

            – RobG
            Oct 24 '11 at 7:28





            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.

            – RobG
            Oct 24 '11 at 7:28













            1














            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.






            share|improve this answer




























              1














              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.






              share|improve this answer


























                1












                1








                1







                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.






                share|improve this answer













                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.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Oct 24 '11 at 3:14









                DarylDaryl

                14.3k454109




                14.3k454109























                    0














                    javascript has a sort function for arrays.



                    You can do



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





                    share|improve this answer




























                      0














                      javascript has a sort function for arrays.



                      You can do



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





                      share|improve this answer


























                        0












                        0








                        0







                        javascript has a sort function for arrays.



                        You can do



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





                        share|improve this answer













                        javascript has a sort function for arrays.



                        You can do



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






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Oct 24 '11 at 3:17









                        IcarusIcarus

                        53.9k1173106




                        53.9k1173106























                            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 :




                            • Simple sorts :


                              • Insertion sort

                              • Selection sort



                            • Efficient sorts :


                              • Merge sort

                              • Heapsort

                              • Quicksort



                            • Bubble sort and variants :



                              • Bubble sort

                              • Shellsort

                              • Comb sort



                            • Distribution sort


                              • Counting sort

                              • Bucket sort

                              • Radix sort








                            share|improve this answer




























                              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 :




                              • Simple sorts :


                                • Insertion sort

                                • Selection sort



                              • Efficient sorts :


                                • Merge sort

                                • Heapsort

                                • Quicksort



                              • Bubble sort and variants :



                                • Bubble sort

                                • Shellsort

                                • Comb sort



                              • Distribution sort


                                • Counting sort

                                • Bucket sort

                                • Radix sort








                              share|improve this answer


























                                0












                                0








                                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 :




                                • Simple sorts :


                                  • Insertion sort

                                  • Selection sort



                                • Efficient sorts :


                                  • Merge sort

                                  • Heapsort

                                  • Quicksort



                                • Bubble sort and variants :



                                  • Bubble sort

                                  • Shellsort

                                  • Comb sort



                                • Distribution sort


                                  • Counting sort

                                  • Bucket sort

                                  • Radix sort








                                share|improve this answer













                                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 :




                                • Simple sorts :


                                  • Insertion sort

                                  • Selection sort



                                • Efficient sorts :


                                  • Merge sort

                                  • Heapsort

                                  • Quicksort



                                • Bubble sort and variants :



                                  • Bubble sort

                                  • Shellsort

                                  • Comb sort



                                • Distribution sort


                                  • Counting sort

                                  • Bucket sort

                                  • Radix sort









                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Feb 29 '16 at 22:59









                                John SlegersJohn Slegers

                                27.8k13147129




                                27.8k13147129























                                    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 ]





                                    share|improve this answer




























                                      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 ]





                                      share|improve this answer


























                                        0












                                        0








                                        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 ]





                                        share|improve this answer













                                        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 ]






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Feb 14 '18 at 19:23









                                        twknabtwknab

                                        691918




                                        691918























                                            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]));





                                            share|improve this answer




























                                              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]));





                                              share|improve this answer


























                                                0












                                                0








                                                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]));





                                                share|improve this answer













                                                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]));






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Nov 22 '18 at 11:00









                                                Fatah Banan WijayaFatah Banan Wijaya

                                                1




                                                1






























                                                    draft saved

                                                    draft discarded




















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function () {
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7870961%2fsorting-arrays-using-for-loop-in-javascript%23new-answer', 'question_page');
                                                    }
                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    Tonle Sap (See)

                                                    I get strange results when I access the Sqlitedatabase with Unity C# via XAMPP

                                                    Guatemaltekische Davis-Cup-Mannschaft