Tim
Tim

Reputation: 306

jQuery object .sort() not sorting

I'm trying to sort a list by it's value but I can't figure out why it doesn't work once I changed it.

The nothing is sorted once I change the a and b part to ipArray[a/b.value].

I can confirm that all the option values exists in the ipArray as I'm able to get those values by using selectList.each(function(){ alert( ipArray[$(this).val()].ipAdd) )

ipArray is an array that has objects of this format

{
     ipAdd : "",
     network : ""
}

id = id of the entry
eg. ipArray[id] = { ip : "1.2.3.4", network: "test network"};


//    Example
var id = $("#list");
var selectList = $("option", id );

selectList.sort(function (a, b) {

    a = a.value;
    b = b.value;

    // Doesn't work. Would like to sort by network name then by ip address
    //a = ipArray[a.value].ipAdd;
    //b = ipArray[b.value].ipAdd;

    return a - b;
});

id.html(selectList);

Edit:

Created a fiddle https://jsfiddle.net/bme4rv6o/12/ With the expected output

Upvotes: 1

Views: 152

Answers (3)

falsarella
falsarella

Reputation: 12447

First, note that a.value is a string. Parse it to int and subtract 1 from it to then use the result as the index.

Finally, use localeCompare to sort strings, instead of subtracting.

Fiddle: https://jsfiddle.net/bme4rv6o/13/

Also, you'll probably need to add more logic to sort function to handle a tie (EG, when both a and b are equal, return an IP comparison (which would also need proper parse for each token separated by the dots)).

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386604

Simply one line of code:

It evaluates the first part and if the network is the same, then the other part is evaluated.

selectList.sort(function (a, b) {
    return a.network.localeCompare(b.network) || a.ipAdd.localeCompare(b.ipAdd);
});

The algorithm is working fine, see below. But your selectList does contain an object, whicht is not sortable like you would like.

var ipArray = [];

function add(ip, network) {
    ipArray.push({ ip: ip, network: network });
}

add("1.1.1.1", "A");
add("2.2.2.2", "B");
add("3.3.3.3", "D");
add("4.4.4.4", "C");
add("5.5.5.5", "A");

ipArray.sort(function (a, b) {
    return a.network.localeCompare(b.network) || a.ip.localeCompare(b.ip);
});

document.write('<pre>' + JSON.stringify(ipArray, 0, 4) + '</pre>');

Upvotes: 0

void
void

Reputation: 36703

You are sorting using a property value which doesn't even exists in the object

selectList.sort(function (a, b) {

     var _network = a.network.localCompare(b.network);
     var _ip  = a.ip.localCompare(b.ip);

     // Will first check network, if equal will then check IP
     return (_network==0?_ip:_network);    

});

Upvotes: 2

Related Questions