How to sort a list alphabetically using YUI3

34 Views Asked by At

I am trying to add items to a list and want the items not to be added at the end but sorted alphabetically. I am using YUI3 and I have a sorting function but when I use it, it adds the items at the end of the list. However, when I refresh the list becomes sorted. Any chance that I sort the list without the need to refresh?

Thanks!

1

There are 1 best solutions below

0
stiemannkj1 On

Is there any reason that you can't just use javascript's built-in Arrays.prototype.sort()?

[ 'a', 'c', 'b' ].sort(); returns [ 'a', 'b', 'c' ] so it should fulfill your requirements, and it seems to have been support by browsers for a very long time.

var unsorted = [ 'a', 'c', 'b' ];
document.getElementById('array').innerHTML = unsorted;

document.getElementById('button').onclick = function() {
  document.getElementById('array').innerHTML = unsorted.sort();
}
<button id="button">Sort</button>
<span id="array"></span>