简体   繁体   English

在Javascript中的数组排序函数中创建自定义数组

[英]Creating a custom array within an array sort function in Javascript

What would i need to put in the SortIP function to make the custom sort function sort the array by the last digit of the IP number. 我需要在SortIP函数中添加什么才能使自定义排序函数按IP号的最后一位对数组进行排序。 This doesn't work. 这行不通。

function SortIP(a, b)
{
    return a[0][3] - b[0][3];
}

LAN = new Array
(
    ["ADSL Router", [192, 168, 0, 1]],
    ["Gary's Mac", [192, 168, 0, 15]],
    ["Network Switch", [192, 168, 0, 2]],
    ["Production Email", [192, 168, 0, 60]]
);
LAN.sort(SortIP);

expected array order: 预期的阵列顺序:

  1. ADSL Router: 192.168.0.1 ADSL路由器:192.168.0.1
  2. Network Switch: 192.168.0.2 网络交换机:192.168.0.2
  3. Gary's Mac: 192.168.0.15 加里的Mac:192.168.0.15
  4. Production Email: 192.168.0.60 生产电子邮件:192.168.0.60

You're comparing the wrong values. 您正在比较错误的值。 Try this: 尝试这个:

function SortIP(a, b) {
    return a[1][3] - b[1][3];
}

You're almost there 你快到了

just replace 只需更换

return a[0][3] - b[0][3];

with

return a[1][3] - b[1][3];

and you're done. 到此为止。

Why? 为什么? Because the IP is the second (Index=1) cell of each array. 因为IP是每个阵列的第二个(Index = 1)单元。

The values sent to the sort handler are values of the array being sorted. 发送到排序处理程序的值是要排序的数组的值。

Since this is a bubble sort, you have to return 0 if the items are the same, 1 if a > b, and -1 if b > a; 由于这是冒泡排序,因此如果项目相同,则必须返回0;如果a> b,则必须返回1;如果b> a,则必须返回-1。

function SortIP(a, b)
{
    if ( a[1][3] == b[1][3] ) return 0;
    return ( a[1][3] > b[1][3] ) ? 1 : -1;
}

change your sort function to: 将您的排序功能更改为:

function SortIP(a, b)
{
    return a[1][3] - b[1][3];
}

If you want to sort by the complete address, it might be a good idea to write a thin wrapper for the array containing the bytes: 如果要按完整地址排序,最好为包含字节的数组编写一个精简包装器:

function IP4() {
    var ip = Array.prototype.slice.call(arguments, 0, 4);
    ip.toString = IP4.toString;
    ip.valueOf = IP4.valueOf;
    return ip;
}

IP4.toString = function() {
    return this.join('.');
};

IP4.valueOf = function() {
    return (this[0] << 24) | (this[1] << 16) | (this[2] << 8) | this[3];
};

var LAN = [
    ["ADSL Router", IP4(192, 168, 0, 1)],
    ["Gary's Mac", IP4(192, 168, 0, 15)],
    ["Network Switch", IP4(192, 168, 0, 2)],
    ["Production Email", IP4(192, 168, 0, 60)]
];

LAN.sort(function(a, b) { return a[1] - b[1]; });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM