0

I've been trying and trying different ways to think outside the box on this one and for some reason I can't get it.

         function sortByLength(array) {
           for(var i = 0; i < array.length; i++) {
             for(var n = 0; n < array.length; n++) {
               array.sort(function(i, n) {
                 return i.length - n.length;
               });
             }
           }
           return array;
        }
          
        console.log(sortByLength(["Hello", "Cheese", "Bye"]));
         
        //expecting ["Bye", "Hello", "Cheese"]

I guess I'm trying to figure out:
1. Why is this an infinite loop?
2. Why can't I simply pass in the looped values of i and n, then compare them to sort them by length?

Any clues or help I can get will be much appreciated. Thanks!

2
  • I ran it in the Chrome Javascript console and it works perfectly fine. It's not an infinite loop. Commented Oct 7, 2017 at 4:12
  • I ran it in codepen and it wouldn't work because it was considered an "infinite loop". Also it won't work as my challenge answer. Commented Oct 7, 2017 at 4:17

2 Answers 2

1

You don't actually need the for-loop's. The i and n loop variables aren't the same as the i and n parameters used by the sorting function, so you are effectively sorting the array array.length squared times.

Just write:

function sortByLength(array){
    array.sort(function(i, n){
        return i.length - n.length;
        });
    return array;
}

console.log(sortByLength(["Hello", "Cheese", "Bye"]));

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I dunno why it didn't work for me the several hundred times I tried it! could have been a possible misspelling or missing semi-colon or something.
0

Why do you try to sort the array n^2 times? It's enough to call sort just once:

sortByLength = function (array){
 array.sort(function(i, n){return i.length - n.length;});
 return array;
}
sortByLength(["Hello", "Cheese", "Bye"]);

(3) ["Bye", "Hello", "Cheese"]

2 Comments

and more direct answers to your questions: 1) it's not an infinite loop. Maybe it takes too long 2) i and n in internal array.sort function are not the same variables, which are in the loop. In sort they are array elements. In for loops they are simple numbers
Thanks Sergey. I don't know know why it wouldn't let me take it because I thought I put that code in without the loops. The loops came about by trying to think "outside" the box because my first several attempts would not work. Thanks again!

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.