0

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);    
1
  • what is the result you desired? Commented Oct 29, 2013 at 3:11

2 Answers 2

2

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

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

Comments

0

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.

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.