IP 排序

最近在做项目的时候,IP 一行行的显示,杂乱无章, 为了看着舒服一点儿,就排序一下。

常规的 IP 一共是4段,栗子:192.168.1.1,那么如果需要排序的话那么需要统一长度, IP 各段大小为 0~255,所以就转换成相同的长度,不满3位的,用0补足,再转为数字就可以实现排序了。

key 是我自己传的一个变量。

public sortIp (arr, key) {
    const ipKey = key || 'value'
    const ipToNumber = (ip: string) => {
      const arrIp: any = [];
      (ip || '').split('.').map(item => {
        item = String(item)
        if (item.length === 1) {
          item = '00' + item
        }
        if (item.length === 2) {
          item = '0' + item
        }
        arrIp.push(item)
      })
      return Number(arrIp.join(''))
    }
    return arr.sort((a, b) => {
      return ipToNumber(a[ipKey]) - ipToNumber(b[ipKey])
    })
  }
原文地址:https://www.cnblogs.com/ruose/p/14653411.html