Help - Search - Members - Calendar
Full Version: JavaScript - calculate Array length
HTMLHelp Forums > Programming > Client-side Scripting
Gooo
Hi

I've got 2 arrays: numberOfwords that has 100 numbers, and wordsArray that has 100 words. numberOfwords and wordsArray must be sorted together.

I'm trying to sort the words in wordsArray according to their lengths. When I call the function below, I get: wordsArray[b] is undefined.

My code:
CODE
function sortPhraseLength()
{
    for(i = 0; i < 100; i++)
    {
        for(b = 0; b < 100; b++)
        {
            if(wordsArray[b].length < wordsArray[i].length)     //the error is here - wordsArray[b] is undefined
            {
                temp = numberOfwords[b];
                numberOfwords[b] = numberOfwords[i];
                numberOfwords[i] = temp;
                    
                tempString = listOfWords[b];
                wordsArray[b] = wordsArray[i];
                wordsArray[i] = tempString;
            }
        }
    }
return null;
}


What am I doing wrong?

Any help will be appreciated.
Thanks
Brian Chandler
This is debugging, so if the JS interpreter says something is undefined, and you think it is (or should be) defined, then usually the interpreter is right.

Is wordsArray declared as a global? Otherwise you won't be able to access it in this function.

Unless you are writing the sort as an exercise (looks like bubble sort, which is very inefficient) it should be better to use the standard Array.sort() method.
Gooo
Thanks for your reply.

var wordsArray = new Array() is declared global.

I changed my code to use the standard Array.sort() method. When I call sortPhraseLength() nothing displays, and there are no errors.

My new sortPhraseLength() function:
CODE
function sortPhraseLength(a, b)
{
    if ( a.length < b.length )
       return -1;
    if ( a.length > b.length )
        return 1;
    return 0;

   for (i = 0; i < 100; i++)
   {
       document.write(wordsArray[i]);
   }
}


The call to sortPhraseLength()
CODE
<body >
   <script type="text/javascript">
        wordsArray.sort(sortPhraseLength);
   </script>
</body>


Why is nothing being displayed?
Brian Chandler
Well, this function: sortPhraseLength is just a comparison function, returning -1, +1 or 0 (which is correct). It gets called inside the sort(). But there's no way the "listing" bit will ever happen, because it's "after" returning.

I think you mean to write out the array *after* calling the sort() -- i.e. in your second bit of code above.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.