如何将数组转换为 <ul><li> 以字母为标题的字母列表

How to convert Array to <ul><li> Alphabetical List with Letters as Headings

我有一个数组 ["Apple", "Orange", "Pineapple"]

如何将其转换为以下列表。

<ul>

<li id = "header">A</li>
<li id = "list" >Apple</li>

<li id = "header">O</li>
<li id = "list" >Orange</li>

<li id = "header">P</li>
<li id = "list" >Pineapple</li>

</ul>

这是您可以采用的方法之一,希望对您有所帮助

var arr = ["Apple", "Orange", "Pineapple"];
var $el = '<ul>';
$.each(arr, function(i, v) {
  $el += '<li id = "header">' + v.slice(0, 1) + '</li>';
  $el += '<li id = "list" >' + v + '</li>';
});
$el += '<ul>';
$('body').append($el);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

var array = ["Apple", "Another-fruit", "Orange", "Pineapple"];

function createList() {
    var list = document.createElement("ul");
    var listItem;
    var currentLetter = '';

    for (var i = 0, length = array.length; i < length; i++) {
        var item = array[i];
        var firstLetter = item.charAt(0);

        if (currentLetter != firstLetter) {
            currentLetter = firstLetter;

            listItem = document.createElement("li");
            listItem.innerHTML = firstLetter;

            list.appendChild(listItem);
        }

        listItem = document.createElement("li");
        listItem.innerHTML = item;

        list.appendChild(listItem);
    }

    return list;
}

document.body.appendChild(createList());

http://jsfiddle.net/bvaughn/edyLg9ga/4/