How to convert Array Alphabetical List with Headings

How to convert Array Alphabetical List with Headings

I have the below working code (from Stackoverflow), the issue is that the expected output should be
  1. <ul> 
  2.       <li>A</li>
  3.       <li>Apple</li>
  4.       <li>Apple2</li>
  5. </ul>
But it generates like below, Please do advise how to resolve this.

  1. <ul> 
  2.       <li>A</li>
  3.       <li>Apple</li>
  4.       <li>A</li>
  5.       <li>Apple2</li>
  6. </ul>

var arr = ["Apple""Apple2", "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);