gpt4 book ai didi

javascript - 仅对数组的部分内容进行排序

转载 作者:行者123 更新时间:2023-12-02 22:11:17 25 4
gpt4 key购买 nike

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

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

为什么会发生这种情况?

最佳答案

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

如果你想按数字排序,那么上面是代码。您的代码按字典顺序对它们进行排序。

关于javascript - 仅对数组的部分内容进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59550625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com