/    Sign up×
Community /Pin to ProfileBookmark

Sorting Alphabetically

Hi,

I have this exercise where I have the following:

[CODE]<script type=”text/javascript”>
//grab user response from prompt
var userResponse=prompt(“Please enter some random words”, “”);
var userResponse2=prompt(“Please enter another set of words”, “”);
//split the user response into spaces
var userResponse_array=userResponse.split(” “);
document.write(userResponse_array.sort());
</script>[/CODE]

I’m trying to determine with the another input which way to sort the words alphabetically. Any ideas how this might be done?

to post a comment
JavaScript

12 Comments(s)

Copy linkTweet thisAlerts:
@JMRKERFeb 27.2008 — Instead of:

var test=userResponse_array[user_response];

Try:

var test += userResponse_array[user_response];
Copy linkTweet thisAlerts:
@ryanbutlerauthorFeb 27.2008 — Ok that worked, but how might I compensate for another input and determine how to sort the words?
Copy linkTweet thisAlerts:
@JMRKERFeb 27.2008 — Will this work for you? ?
[code=php]
<html>
<head>
<title>Sorted Words</title>
</head>
<script type="text/javascript">
function GetWords() {
//grab user response from prompt
var userResponse1=prompt("Please enter some random words", "");
var userResponse2=prompt("Please enter another set of words", "");
//split the user response into spaces
var userResponse_array1=userResponse1.split(" ");
var userResponse_array2=userResponse2.split(" ");
// display information entered in sorted order
document.getElementById('sortedList1').value = userResponse_array1.sort().join('n');
document.getElementById('sortedList2').value = userResponse_array2.sort().join('n');
}

</script>
<body>
<button onClick="GetWords()">Collect words</button><br />
<textarea id="sortedList1" rows="20"></textarea>
<textarea id="sortedList2" rows="20"></textarea>
</body>
</html>
[/code]

May need further modification if 'case' of the words entered is significant.
Copy linkTweet thisAlerts:
@mrhooFeb 27.2008 — By collecting distinct words as property names and giving them the value of the number of times they appear,

you can sort the words by frequency or alphabetically.

You can get the string from anywhere-

from an input, a textarea, an AJAX response, or a whole page.

[CODE]var Wordman= {
tlcSort: function(a,b){
if(a[0]== b[0]) return 0;
if(a[0].toLowerCase() > b[0].toLowerCase()) return 1;
return -1;
},
grabWords: function(str,sorter){
var T=this;
var G= {}, A= [],word,W;
T.wordcount= 0;
var Rx= /([a-z]+((-|')[a-z]+)?)/ig;
while(str && (word= Rx.exec(str))!= null){
word= word[1].toLowerCase();
word= word.charAt(0).toUpperCase()+word.substring(1);
if(!G[word])G[word]= 0;
G[word]+= 1;
++T.wordcount;
}
for(var w in G){
A.push([w,G[w]]);
}
T.uniquewords= A.length;
if(sorter=== true){
A.sort(T.tlcSort);
return A;
}
A.sort(function(a,b){
if(b[1]== b[2])return T.tlcSort(a,b);
return b[1]-a[1];
})
return A;
}
}[/CODE]


// example- use any string from anywhere.
[CODE]Wordman.demo=function(str){
var T=this;
var S= [];
S.push(T.grabWords(str).join('; '));
S.push(T.grabWords(str,true).join('; '));
if(T.uniquewords){
var s1= T.uniquewords+' unique words of '+
T.wordcount+ ' total wordsn';
alert(s1+'Alphabetic Sort:n'+S[0]);
alert(s1+'Use (Frequency) Sort:n'+S[1]);
}
else alert('No words found')
}
Wordman.demo(document.body.innerHTML);[/CODE]
Copy linkTweet thisAlerts:
@mrhooFeb 27.2008 — I really miss being able to edit these posts- this is the corrected version,

maybe a kind moderator would remove the previous one....
Copy linkTweet thisAlerts:
@mrhooFeb 27.2008 — By collecting distinct words as property names and giving them the value of the number of times they appear,

you can sort the words by frequency or alphabetically.

You can get the string from anywhere-

from an input, a textarea, an AJAX response, or a whole page.

[CODE]var Wordman= {
tlcSort: function(a,b){
if(a[0].toLowerCase()== b[0].toLowerCase()) return 0;
if(a[0].toLowerCase() > b[0].toLowerCase()) return 1;
return -1;
},
grabWords: function(str,sorter){
var T= this;
var G= {}, A= [],word,W;
T.wordcount= 0;
var Rx= /([a-z]+((-|')[a-z]+)?)/ig;
while(str && (word= Rx.exec(str))!= null){
word= word[1].toLowerCase();
word= word.charAt(0).toUpperCase()+word.substring(1);
if(!G[word])G[word]= 0;
G[word]+= 1;
T.wordcount+= 1;
}
for(var w in G){
A.push([w,G[w]]);
}
T.uniquewords= A.length;
if(sorter=== true){
A.sort(T.tlcSort);
return A;
}
A.sort(function(a,b){
if(b[1]== a[1]) return T.tlcSort(a,b);
return b[1]-a[1];
})
return A;
}
}[/CODE]

// example- use any string from anywhere.
[CODE]Wordman.demo= function(str,boo){
var T= this;
var s= (boo=== true)?'Alphabetic Sort:n':'Use (Frequency) Sort:n';
var s2= T.grabWords(str,boo).join('; ');
if(T.uniquewords){
alert(T.uniquewords+' unique words of'+
T.wordcount+ ' total wordsn'+s+s2);
}
else alert('No words found')
}

Wordman.demo(document.body.innerHTML);
Wordman.demo(document.body.innerHTML,true);[/CODE]
Copy linkTweet thisAlerts:
@ryanbutlerauthorFeb 27.2008 — Will this work for you? ?
[code=php]
<html>
<head>
<title>Sorted Words</title>
</head>
<script type="text/javascript">
function GetWords() {
//grab user response from prompt
var userResponse1=prompt("Please enter some random words", "");
var userResponse2=prompt("Please enter another set of words", "");
//split the user response into spaces
var userResponse_array1=userResponse1.split(" ");
var userResponse_array2=userResponse2.split(" ");
// display information entered in sorted order
document.getElementById('sortedList1').value = userResponse_array1.sort().join('n');
document.getElementById('sortedList2').value = userResponse_array2.sort().join('n');
}

</script>
<body>
<button onClick="GetWords()">Collect words</button><br />
<textarea id="sortedList1" rows="20"></textarea>
<textarea id="sortedList2" rows="20"></textarea>
</body>
</html>
[/code]

May need further modification if 'case' of the words entered is significant.[/QUOTE]


Ok, so if I wanted to sort the array based on the second user response to either ascending or descending order, would that be through an IF statement of some kind to then display it appropriately?
Copy linkTweet thisAlerts:
@JMRKERFeb 27.2008 — Uncertain on how to answer. Do you mean: ?

1. Sort which array ... 1st or 2nd or both?

2. Reverse sort one or both based on what? A checkbox? A radio button?

Or forced direction that is hard coded with the 'IF' statement based upon what decision?

3. Are the two user inputs supposed to be merged into the second display

or kept as is with the two different list displays?

So many questions ... so little time. ?
Copy linkTweet thisAlerts:
@ryanbutlerauthorFeb 27.2008 — Just sort the first array based on the decision from the second ("asking which precedence they prefer") with a hard "if statement" would probably do the trick.
Copy linkTweet thisAlerts:
@JMRKERFeb 27.2008 — Sorry for my confusion, but:

Where is the decision based upon random words entered into the second array by the user?

Is this the sequence you want to see by the program? ?

A. User is prompted to enter some random words

B. Displays those words in entered order in first textarea box

C. User clicks on button (button or checkbox or radio button):

Button #1 will sort in ascending order

Button #2 will sort in decending order

D. Sorted display in second textarea box based upon button selected in C.

If this is desire, why have 2 user entry prompts?

I'm sorry that I'm not a mind reader. ?

What is purpose of second user entry?
Copy linkTweet thisAlerts:
@ryanbutlerauthorFeb 28.2008 — I think the intended functionality of this is like this:

[LIST]
  • [*]First user prompt is taking random words or an input string, however you want to look at it


  • [*]Second user prompt is asking whether the visitor wants the information from first user prompt sorted ascending or descending.


  • [*]Based on the input from the second user prompt, display the array from the first user prompt either in ascending or descending.

  • [/LIST]


    Basically it was an assignment and I was asking for a little direction on how to check the second user prompt. I came up with this that makes sense except my descending order isn't working.

    [CODE]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>4.7</title>
    <head>

    </head>

    <body>
    <script type="text/javascript">

    function des(a,b){

    if(a > b){
    return 1;
    }
    else{
    return -1;
    }

    }

    function GetWords() {
    //grab user response from prompt
    var userResponse1=prompt("Please enter some random words", "");
    var userResponse2=prompt("Would you like to sort the array in Ascending order or Descending order?", "");
    //split the user response into spaces
    var userResponse_array1=userResponse1.split(" ");
    var userResponse_array2=userResponse2.split(" ");
    // display information entered in sorted order

    var a=userResponse2.substring(0,1);

    //alert(userResponse_array1.length);

    if(a=="A"){
    document.getElementById("here").innerHTML=userResponse_array1.sort();
    }
    else{
    document.getElementById("here").innerHTML=userResponse_array1.sort(des);
    }
    }

    </script>
    <body>
    <p id="here"></p>
    <button onClick="GetWords()">Collect words</button><br />
    </body>
    </html> [/CODE]
    Copy linkTweet thisAlerts:
    @JMRKERFeb 28.2008 — If all you are trying to do is collect, display and sort words ups and down, then consider this:
    [code=php]
    <html>
    <head>
    <title>Sorted Words</title>
    </head>
    <script type="text/javascript">
    var userResponse_array = new Array();
    function GetWords() {
    //grab user response from prompt
    var userResponse=prompt("Please enter some random words", "");
    //split the user response into spaces
    userResponse_array=userResponse.split(" ");
    // display information entered in entered order
    document.getElementById('entryList').value = userResponse_array.join('n');
    }
    function SortUpWords() {
    userResponse_array.sort();
    document.getElementById('sortedList').value = userResponse_array.join('n');
    }

    function SortDownWords() {
    userResponse_array.reverse();
    document.getElementById('sortedList').value = userResponse_array.join('n');
    }

    </script>
    <body>
    <button onClick="GetWords()">Collect words</button>
    <button onClick="document.getElementById('entryList').value=''">Clear</button>
    <br />
    <textarea id="entryList" rows="20"></textarea>
    <textarea id="sortedList" rows="20"></textarea><br />
    <button onClick="SortUpWords()">Ascending Sort</button>
    <button onClick="SortDownWords()">Decending Sort</button>
    </body>
    </html>
    [/code]

    Modify to your heart's content.
    ×

    Success!

    Help @ryanbutler spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.22,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...