每天一点前端知识 - 数组排序

164 阅读1分钟

实现

const sort = (arr, key = null, desc = false) => {
  return [...(arr || [])].sort((x, y) => {
    const a = key ? x[key] : x;
    const b = key ? y[key] : y;
    if (!isNaN(Number(a)) && !isNaN(Number(a))) {
      return desc ? b - a : a - b;
    }
    if (typeof a === 'string' && typeof b === 'string') {
      return desc ? b.localeCompare(a) : a.localeCompare(b);
    }
    if (typeof a === 'string' && typeof b === 'number') {
      return desc ? -1 : 1;
    }
    if (typeof a === 'number' || typeof a === 'string') {
      return desc ? 1 : -1;
    }
    return desc ? -1 : 1;
  });
};

使用

sort(arr, key = null, desc = false)

- arr:数组
- key:根据 `key` 值来排序
- desc:是否为降序,默认 `false`

示例

const arr = [
  {
    path: '/a',
    name: 'a',
  },
  {
    path: '/a/1',
    name: 'a1',
  },
  {
    path: '/c',
    name: 'c',
  },
  {
    path: '/a/3',
    name: 'a3',
  },
  {
    path: '/b/1',
    name: 'b1',
  },
  {
    path: '/c/1',
    name: 'c1',
  },
  {
    path: '/b',
    name: 'b',
  },
  {
    path: '/c/2',
    name: 'c2',
  },
  {
    path: '/a/2',
    name: 'a2',
  },
  {
    path: '/b/2',
    name: 'b2',
  },
  {
    path: '/b/1/1',
    name: 'b11',
  },
];

sort(arr, 'path');

11.png

11-result.png

演示地址:ihuxy.com/play?utils=…