Search code examples
javascriptarrayssortingmultidimensional-arraycolumnsorting

Only Parts of Array Are Sorted


For some reason the sort method is properly sorting two chunks of the array, but then missorts those two chunks...

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)
})

Original output:

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

Expected output:

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:", ... ]

Actual output:

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:", ... ]

Why is this happening?


Solution

  • 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)
    })
    

    if you want to sort them numerically, then above is the code. Your code is sorting them lexicographically.