Reputation: 11
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!
Upvotes: 0
Views: 41
Reputation: 4467
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"]));
Upvotes: 1
Reputation: 36
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"]
Upvotes: 0