-1

I am trying to sort a page of logos alphabetically and so have placed the logo name in a H1 tag and have used the code below, however, the logos are not being ordered properly. Can anyone see what is wrong?

var $divs = $("div.box");

$('#alphBnt').on('click', function () {
    var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
        return $(a).find("h1").text() > $(b).find("h1").text();
    });
    $("#container").html(alphabeticallyOrderedDivs);

https://jsfiddle.net/4pkrnb6v/2/

Can anyone help?

LeeTee
  • 6,401
  • 16
  • 79
  • 139
  • 2
    It is **NOT** okay to just delete [your closed question](http://stackoverflow.com/q/43051505/157247) and repost it. It was closed *for a reason*. See the linked question's answers, they answer your question. – T.J. Crowder Mar 27 '17 at 16:33
  • I made a mess of the other post so started again – LeeTee Mar 27 '17 at 16:35
  • But the previous one was closed for a reason. Please read the duplicate. – Rory McCrossan Mar 27 '17 at 16:36
  • Its not a duplicate, the other solution is not what I want – LeeTee Mar 27 '17 at 16:36
  • And this question is almost exactly the same. I don't see how you "made a mess" of the other one. – T.J. Crowder Mar 27 '17 at 16:36
  • You want to sort the elements alphabetically, right? That's what the other question's answers show you how to do. (Where you're going wrong, btw, is in two places: 1. You're using an undocumented method of jQuery objects [`sort` isn't documented], and 2. You're returning a boolean out of its callback -- whereas it should be a number, like Array#sort's callback.) – T.J. Crowder Mar 27 '17 at 16:37
  • I would have to completely rewrite the code, when the answer is much simpler, see below. – LeeTee Mar 27 '17 at 16:40
  • Can you validate my answer ? :) – Liberateur Mar 27 '17 at 16:47

1 Answers1

0

Sort function need return -1 1 OR 0, so just change :

return $(a).find("h1").text() > $(b).find("h1").text();
return $(a).find("h1").text() > $(b).find("h1").text() ? -1 : 1;

source: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/sort

Liberateur
  • 1,337
  • 1
  • 14
  • 33