开发者

JS: loop through strings, find first letter, output as letter group anchor to associated string(s)?

Scenario: I have content that is alphabetically output into a list from a resource library. I need to be able to loop through each element/item (e.g.: department name) in this list and group all starting with 'A' ('B', 'C', 'D', and so on) into its own class for anchor navigation. Then, I need to be able to find which letters were found and create group anchors.

Desired Output: At the top of the page, there is each letter of the alphabet found that has element(s) with that letter. Clicking on the letter will anchor to a section/div (new class) with all elements of the corresponding letter.

What I've Tried (to find the first letter and create a group):

    for(var i=0; i<input_1.length; i++){ //input_1 is the name of the specific resource library
   var firstChar = input_1[i].charAt(0)
   var newGroup = firstChar + "_input_1";
   if(typeof(window[newGroup]) == 'undefined') window[newGroup] = []; //if var doesn't exist, create it
   window[newGroup].push(input_1[i]);
}
A_input_1 = []; //A-letter-specific group

I开发者_如何学JAVA'm beside myself when it comes to creating an anchor from that group to the associated strings. Ideas?


You need to use DOM functions to manipulate the DOM. It's kind of a pain, actually. To be honest, I wouldn't mess with it; there are libraries that make things easier. Let's go with JQuery.

Say your page has the following HTML:

<ul id="TheList">
    <li>Auspicious</li>
    <li>Brobdingnagian</li>
    <li>Calico</li>
    <li>Doppleganger</li>
    <li>Etc.</li>
</ul>

JQuery code to manipulate it would look something like this (I have not tested this code to ensure it works):

var previousFirst = null;
$('#TheList').each(function() {
    var text = $(this).text();
    if (previousFirst === null)  previousFirst = $(this);

    $(this).addClass(text.charAt(0) + '_input_1');

    if (text.charAt(0) != previousFirst.text().charAt(0))  {
        $('<a name="'+ previousFirst.text().charAt(0) +'"></a>').prependTo(previousFirst);
        previousFirst = $(this);
    }
});

If you're not familiar with JQuery, I encourage you to read up on it on jquery.com. Once you familiarize yourself with the workings of the library, the code should be clear and easy to understand. That said, if you need any clarification, feel free to ask and I'll do my best.


Off the top of my head I can't think of a native method that will do this more elegantly than a loop over all elements in the list. Performance may thus be an issue if you have a large number of items or on slow client browsers.

Bearing the above in mind, here's one approach:

var length = input_1.length;
var groups = {};

for ( var i = 0; i < length; i ++ )
{
    var item      = input_1[ i ];
    var firstChar = item.charAt( 0 );

    groups[ firstChar ] = groups[ firstChar ] || [];
    groups[ firstChar ].push( item );
}

The value of 'length' is calculated externally as a very small optimisation in loops - JavaScript will re-evaluate the array length each time around the loop otherwise. Other than that, the end result from an input array of strings is that "groups" will have a series of keys / properties corresponding to all the used first letters of the input strings and each of those keys has, as its value, an array of the grouped strings. Sorting is not attempted.

Example:

input_1 = [ "hello", "an", "cat", "hi", "henry", "thing", "anchor" ];

=> groups[ "a" ] is [ "an", "anchor" ]
   groups[ "c" ] is [ "cat" ]
   groups[ "h" ] is [ "hello", "hi", "henry" ]
   groups[ "t" ] is [ "thing" ]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜