仅对阵列的部分进行排序

时间:2020-01-01 07:09:17

标签: javascript arrays sorting multidimensional-array columnsorting

由于某种原因,sort方法对数组的两个块进行了正确排序,但是随后对这两个块进行了错误排序...

cp.exec('wmic logicaldisk get freespace,name,size,volumename', (error, stdout)=>{
  drives = stdout.trim().split('\r\r\n')
    .map(value => value.trim().split(/\s{2,}/))
    .slice(1)

    .sort((aa,ba)=>{
      const
        a = aa[0],
        b = ba[0]
      if (a < b) return -1
      else if (a > b) return 1
      else return 0
    })

    console.log(drives)
})

原始输出:

0: [ ... "C:", ... ]
1: [ ... "D:", ... ]
2: [ ... "E:", ... ]
3: [ ... "F:", ... ]
4: [ ... "G:", ... ]
5: [ ... "H:", ... ]
6: [ ... "I:", ... ]
7: [ ... "J:", ... ]
8: [ ... "K:", ... ]

预期输出:

5: [  "559056044032", "C:", ... ]
6: [  "788449492992", "G:", ... ]
7: [  "945300619264", "K:", ... ]
8: [  "999369699328", "D:", ... ]
//
0: [ "1511574335488", "E:", ... ]
1: [ "2296009408512", "H:", ... ]
2: [ "3507750227968", "J:", ... ]
3: [ "3594248679424", "I:", ... ]
4: [ "4620751712256", "F:", ... ]

实际输出:

0: [ "1511574335488", "E:", ... ]
1: [ "2296009408512", "H:", ... ]
2: [ "3507750227968", "J:", ... ]
3: [ "3594248679424", "I:", ... ]
4: [ "4620751712256", "F:", ... ]
// it properly sorts each of these two chunks but
// then it arranges the chunks in the wrong order
5: [  "559056044032", "C:", ... ]
6: [  "788449492992", "G:", ... ]
7: [  "945300619264", "K:", ... ]
8: [  "999369699328", "D:", ... ]

为什么会这样?

1 个答案:

答案 0 :(得分:1)

cp.exec('wmic logicaldisk get freespace,name,size,volumename', (error, stdout)=>{
  drives = stdout.trim().split('\r\r\n')
    .map(value => value.trim().split(/\s{2,}/))
    .slice(1)

    .sort((aa,ba)=>{
      const
        a = Number(aa[0]),
        b = Number(ba[0])
      if (a < b) return -1
      else if (a > b) return 1
      else return 0
    })

    console.log(drives)
})

如果要对它们进行数字排序,则上面是代码。 您的代码按字典顺序对其进行排序。

相关问题