javascriptjqueryintel-xdkappframework

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


I have an Array ["Apple", "Orange", "Pineapple"]

How do i convert it to the below list.

<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>

Solution

  • this is one of the way you can do it hope this will help you

    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>