Adam
Adam

Reputation: 832

Javascript sort method

I am working with a bit of code on a website and I am trying to order the results by member id (I've left comments in the code below where this is) it doesnt seem to sort the order of the results though so I guess I must be doing something wrong. Does anyone know what the issue is, and perhaps how I could limit the amount of results shown to about 10 please?

var httpRequestObject = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Wcf/Search.svc/TestSearch",
dataType: "json",
success: function (response) {

    if (response != null && response.d != null) {
        var data = response.d;
        if (data.ServiceOperationOutcome == 10) {

            var profileList = data.MemberList;
            if (profileList != null && profileList.length > 0) {
                for (var i = 0; i < profileList.length; i++) {
                    var profile = profileList[i];

                    // sort var
                    var memberId = (profile.MemberId);


                    if (profile != null) {
                        var clonedTemplate = $('.profile-slider #profile').clone();
                        $(clonedTemplate).removeAttr('style').removeAttr('id');
                        $(clonedTemplate).find('img').attr("src", profile.ThumbnailUrl).attr("alt", profile.Nickname).wrap('<a></a>');
                        $(clonedTemplate).appendTo('.profile-slider');

                        // sort
                        $(memberId).sort();
                    }
                }

            }
        }

        else {
            alert("Error code " + String(data.ServiceOperationOutcome));
        }
    }

    else {
        alert("Null data");
    }
},

error: function (jqXHR, textStatus, errorThrown) {
    alert(errorThrown);
}

});

Upvotes: 1

Views: 126

Answers (2)

sabof
sabof

Reputation: 8192

As adeneo said, you probably want to sort the Member list.

profileList = profileList
  .filter(function (arg) {return arg !== null;}) // remove nulls
  .sort(function(a, b) {
    return a.MemberId < b.MemberId ? -1 : 1; // the < operator works for numbers or strings
  });

Upvotes: 3

adeneo
adeneo

Reputation: 318182

jQuery doesn't have a sort method, but there is Array.sort() which is probably what you're looking for, but profile seems to be an object inside the array data.MemberList, so you should probably sort that before iterating over it:

var profileList = data.MemberList; // array
profileList.sort(function(a,b) {
    return a.MemberId.localeCompare(b.MemberId);
});

for (var i = 0; i < profileList.length; i++) {
   // do stuff to each item in the now sorted array
}

Upvotes: 3

Related Questions