Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to take the contents of a list, that is not in alphabetical order, then by adding each item to an array, sort them into alphabetical order and insert them back into the list in alphabetical order.

Plain language: I need to alphabetize a list using JS or jQuery.

Here's what I have. I just can't figure out how to insert the contents of the array in back into the list.

Thank you all in advance :)

var sectors = [];
$("li").each(function() { sectors.push($(this).text()) });
sectors.sort();
console.log(sectors);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<ul>
  <li id="alphabet">B</li>
  <li id="alphabet">C</li>
  <li id="alphabet">A</li>
</ul>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
98 views
Welcome To Ask or Share your Answers For Others

1 Answer

There's no need to generate an array here, you can use the sort() method directly on the jQuery object resulting from selecting the li elements. After sorting you can then append them back to the parent ul in the corrected order. Try this:

$("li").sort(function(a, b) {
    var aText = $(a).text(), bText = $(b).text();
    return aText < bText ? -1 : aText > bText ? 1 : 0;
}).appendTo('ul');

Updated fiddle

Also note that having duplicate id attributes in a document is invalid. Your #alphabet elements should be changed to use a class instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...