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); 
1

2 Answers 2

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;
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome. Do you know how I can fix the second problem?
@Thomasdc simply return a.name.length - b.name.length;
But how do I make it sort it alphabetically after being sorted by length then? So if I have ABA, BBBB, AAAA, AAA. It should be AAAA, BBBB, AAA, ABA
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);
}

3 Comments

I have already tried this and it doesn't work. Nothing happens. jsfiddle.net/sbe8yzv0/10
please try edit. you need to address the name property.
Very nice. Thanks a lot! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.