以特定方式对对象进行多排序数组

时间:2019-09-02 12:32:18

标签: javascript arrays sorting

有一系列对象

ar = [
    {name: 'a', count: 1},
    {name: 'c', count: 2},
    {name: 'f', count: 0},
    {name: 'e', count: 0},
    {name: 'b', count: 3},
    {name: 'a', count: 0},
];

我正在尝试通过以下方式对它进行排序

  1. 计数> 0

  2. 按字母顺序命名

所以结果数组将是

ar = [
    {name: 'a', count: 1},
    {name: 'b', count: 3},
    {name: 'c', count: 2},
    {name: 'a', count: 0},
    {name: 'e', count: 0},
    {name: 'f', count: 0},
];

我尝试了几种多重排序方法,结果总是很接近,但是计数为0的部分没有正确排序。

2 个答案:

答案 0 :(得分:1)

您可以减去count > 0返回的布尔值。这将优先排序count > 0的项目。如果两个项目具有相同的优先级,请使用localeCompare

根据name属性对它们进行排序

const arr = [
  { name: 'a', count: 1 },
  { name: 'c', count: 2 },
  { name: 'f', count: 0 },
  { name: 'e', count: 0 },
  { name: 'b', count: 3 },
  { name: 'a', count: 0 },
];

arr.sort((a, b) => (b.count > 0) - (a.count > 0) || a.name.localeCompare(b.name))

console.log(arr)

答案 1 :(得分:1)

好的。为什么不使用简单明了的方式?我的意思是将一个数组分为2个数组:一个数组,其中所有项的count> 0,第二个数组,其余的项。然后按字母顺序对两者进行排序。然后将concat阵列退回。

    const ar = [
        {name: 'a', count: 1},
        {name: 'c', count: 2},
        {name: 'f', count: 0},
        {name: 'e', count: 0},
        {name: 'b', count: 3},
        {name: 'a', count: 0},
    ];
    
    const pCount = [];
    const nCount = [];
    ar.forEach((item) => {
        if (item.count > 0) {
            pCount.push(item);
        } else {
            nCount.push(item);
        }
    });
    
    pCount.sort((a, b) => a.name.localeCompare(b.name));
    nCount.sort((a, b) => a.name.localeCompare(b.name));
    
    const result = [...pCount, ...nCount]; // concat 
    console.log(result);