2

Code I am talking about: https://jsfiddle.net/sbe8yzv0/8/

I want to sort my array by the name with two buttons: First button sorts it by length and second buttons sorts it by alphabet.

When I sort by alphabet it doesn't want to function. It randomly puts the data in different positions. I have tried multiple ways of sorting it and they all act funky and doesn't sort it completely alphabetically. What can I do to make it actually sort the name in array by alphabet?

    function sortNameAlphabetically(a, b) {
        return a.name > b.name;
    }

The sort by length is working as intended except when it sorts alpabeticly after length it does it bakwards. How do I make sure it sorts the right way?

    function sortNameByLength(a, b) {
        return b.name.length - a.name.length;
        a.localeCompare(b); 
Thomasdc
  • 55
  • 5
  • [Your first comparison function is invalid](http://stackoverflow.com/q/24080785/1048572). – Bergi Jun 14 '16 at 14:14

2 Answers2

2

change the sortNameAlphabetically method to

  function sortNameAlphabetically(a, b) {
        return a.name.localeCompare( b.name );
    }

updated fiddle

Also, statement after return statement in sortNameByLength method is not reachable and not required anyways.

    function sortNameByLength(a, b) {
        return b.name.length - a.name.length;
    }
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1

Part two of the question, to maintain the alphabetical sorting after length sorting, you can use a logical OR with the localeCompare method.

function sortNameByLength(a, b) {
    return b.name.length - a.name.length || a.name.localeCompare(b.name);
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392