I encountered a problem in the project and needed to sort the IP addresses:

let arr = ["10.3.72.160", "10.3.71.106", "10.3.71.102", "10.3.69.108"]

The idea is very simple, to implement a function to compare two version numbers, then as an array sort method compareFunction passed.

function compare(a, b) {
  const a1 = a.split(".");
  const a2 = b.split(".");
  // IP 地址一共 4 位
  for (let n=0; n<4; n++) {
    const i = +a1[n];
    const j = +a2[n];
    if (i < j) return -1;
    else if (i > j) return 1;
  }
  return 0;
}
arr.sort(compare);

Then it is a bit difficult to sort the version numbers, because the number of digits in the version number is not fixed. It is assumed that the version number is at most three digits, that is, the version number can take 1-3 digits:

const versions = [
    '0.5.1',
    '0.1.1',
    '2.3.3',
    '0.302.1',
    '4.2',
    '4.3.5',
    '4.3.4'
];

Still the same, to implement a function to compare two version numbers, then as an array sort method compareFunction Incoming:

function compare(a, b) {
  const a1 = a.split(".");
  const a2 = b.split(".");
  // 版本号可以取 1-3 位
  // 位数不足就补零
  for (let n=0; n<3; n++) {
    const i = (n < a1.length) ? +a1[n] : 0;
    const j = (n < a2.length) ? +a2[n] : 0;
    if (i < j) return -1;
    else if (i > j) return 1;
  }
  return 0;
}
versions.sort(compare);

Here is a little trick. The array sort method can actually be sorted without passing compareFunction

["10.3.72.160", "10.3.71.106", "10.3.71.102", "10.3.69.108"].sort();
// ['10.3.69.108', '10.3.71.102', '10.3.71.106', '10.3.72.160']

According to the MDN documentation, if compareFunction is not specified, the elements will be sorted according to the Unicode positions of the characters in the converted string.

refer to:

Array.prototype.sort() - MDN


一杯绿茶
199 声望17 粉丝

人在一起就是过节,心在一起就是团圆