Reputation: 101
Is there a way to set my for loop to hit all instances of string[i].length == length
before decreasing the value of length by 1? I have messed around with adding while loops but I can't quiet get it.
This script is meant to order an array from greatest to least based on the length of each item. Only problem is I can't figure out how to order it without skipping array item lengths that have already been detected.
var string = ["hello", "world", "fishing", "before", "all", "test"];
var length = 0;
word = 0;
for (x = 0; x < string.length; x++) {
if (string[x].length > length) {
var length = string[x].length;
word = string[x];
}
}
string1 = [];
for (i = 0; i < string.length; i++) {
if (string[i].length == length) {
length = string[i].length - 1;
string1.push(string[i]);
i = 0;
}
}
console.log(string1);
Upvotes: 0
Views: 145
Reputation: 388446
why not use Array.sort()
var string = ["hello", "world", "fishing", "before", "all", "test"];
string.sort(function(o1, o2){
return o1.length - o2.length;
})
console.log(string)
Demo: Fiddle
Manual Sorting: Fiddle
Upvotes: 2
Reputation: 57222
Why not use javascript's build in sort
function http://www.w3schools.com/jsref/jsref_sort.asp
You can pass it a sortfunction
- use that to compare the string's length and let javascript do the sorting for you.
Upvotes: 0