Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

javascript - Alphabetize a list using JS or jQuery

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...