Javascript for loop through array listing name and beginning letter

时间:2015-07-29 00:07:32

标签: javascript arrays for-loop

I'd like to loop through an array and show the name of each entry and if it's the first entry of a letter show the first letter as a grouping.

Desired result

Private Sub List35_AfterUpdate()
Dim myTopic As String
myTopic = "Select * from FormsHelpTable where ([ID] = " & Me.List35 & ")"
Me.Form.RecordSource = myTopic
Me.Comment.Requery
End Sub

<h1>A</h1>
        <ul>
            <li>Alligator</li>
            <li>Ant</li>
        </ul>
    <h1>B</h1>
        <ul>
            <li>Bat</li>
            <li>Bear</li>
        </ul>
    <h1>K</h1>
        <ul>
            <li>Kanagroo</li>
        </ul>

Any ideas what I'm doing wrong or how I should go about accomplishing this?

3 个答案:

答案 0 :(得分:1)

Not sure why you're putting it into another structure, seems unnecessary.

Void

答案 1 :(得分:0)

Try this one:

Example& operator = (const Example& rhs) = delete;

答案 2 :(得分:0)

I would make var children = ['Kangaroo', 'Alligator', 'Ardvark', 'Ant', 'Bear', 'Bat', 'Cat', 'Cow']; children.sort(); var char = ''; var output = ""; for (var i = 0; i < children.length; i++) { var child = children[i]; var cLetter = child.charAt(0); if (cLetter !== char) { if (output.length) output += '</ul>'; output += '<h1>' + cLetter + '</h1><ul>'; char = cLetter; } output += '<li>' + child + '</li>'; } if (output.length) output += '</ul>'; document.write(output); an object, with the first letter as keys holding arrays of the names as the values.

aZ

Then iterate and create keys if they aren't already present, and in the same loop I'd make a map of the letters to be sorted later to get the order correct.

Then it's just a matter of iterating and creating proper elements

var aZ = {};

It's more code, and a lot more verbose and readable so it's easier to see what's going on.