首页 > 解决方案 > 字母数字/自然对 Javascript 中带有前导零的数组进行排序

问题描述

我需要对包含字母/数字/和前导零的字符串数组进行排序。如果为 null,则它必须位于列表顶部并显示为空字符串。我已经查看和研究了许多不同的方式,但没有任何一种方式能像我期望的那样。

初始数组:

input = [
    { value: null },
    { value: '' },
    { value: '-' },
    { value: '0' },
    { value: 'A1' },
    { value: '0001' },
    { value: '01' },
    { value: '1' },
    { value: '01.008A' },
    { value: '01.008' },
    { value: '02' },
    { value: 'A' },
    { value: '10' },
    { value: '100A1' },
    { value: '10-1' },
    { value: '100' },
    { value: '001' },
    { value: '2' },
  ]

预期输出:

  1. " "
  2. " "
  3. “——”
  4. “0”
  5. “0001”
  6. “001”
  7. “01”
  8. “01.008”
  9. “01.008A”
  10. “1”
  11. “02”
  12. “2”
  13. “10”
  14. “10-1”
  15. “100”
  16. “100A1”
  17. “一种”
  18. “A1”

编辑:(我的原始代码)

function sortAlphanumeric<T>(this: Array<T>, property: string): Array<T> {
  var collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });

  function dynamicSort(property) {
    var sortOrder = 1;

    if (property[0] === "-") {
      sortOrder = -1;
      property = property.substr(1);
    }

    return function (a, b) {
      if (sortOrder == -1) {
        return b[property].localeCompare(a[property]);
      } else {
        return a[property].localeCompare(b[property]);
      }
    }
  }
  return this.sort(dynamicSort(property)).sort((a, b) => {
    var nullToEmptyString = '';

    if (a[property] === null) {
      a[property] = nullToEmptyString;
    }

    if (b[property] === null) {
      b[property] = nullToEmptyString;
    }
    return collator.compare(a[property], b[property]);
  });
}

标签: javascriptsortingalphanumericnatural-sort

解决方案


这应该这样做:

input.sort(({value:a}, {value:b}) => {
  const ai = parseInt(a, 10), bi = parseInt(b, 10);
  return (b == null) - (a == null)
    || (ai - bi)
    || (a > b) - (b > a);
}).map(x => x.value || "")

推荐阅读