0

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?

oldboy
  • 5,729
  • 6
  • 38
  • 86
  • isn't second one sorting the full array correctly according to your demonstration above?? – shahin mahmud Jan 01 '20 at 07:23
  • @shahinmahmud no its not. the order should be CGKD-EHJIF which is smallest to largest, but instead the order is EHJIF-CGKD. the drive with the least amount of free space that should be placed at the beginning of the array is drive C. the two chunks are properly ordered independent from one another, but are mutually out of order – oldboy Jan 01 '20 at 07:26
  • free space => "1511574335488", you want to sort them numerically?? – shahin mahmud Jan 01 '20 at 07:28
  • @shahinmahmud correct. the first item in each nested array at index `0` is the disks `freespace`, and i am trying to sort them from smallest to largest `freespace` – oldboy Jan 01 '20 at 07:29
  • Just use `.sort((aa,ba) => aa[0] - ba[0])` – adiga Jan 01 '20 at 07:48

1 Answers1

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

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

shahin mahmud
  • 945
  • 4
  • 11