我需要对node.js
中的字符串数组进行排序。我正在使用underscore
库,对于以下数组,它没有执行应做的工作。
这是数组:
var stringsArray =
['2b9ee0e611af977edbfd6bb04a56ebe05af07bdbc2daf88e5617fb872487f27c',
'6f009f9cb714849dba36a302d96dcd940c803bab5aa72dc25f52c26d2a32aab6',
'980942c275b7a407650980d6be561e6260edc55316247f20c3250ffc4d3d3c2f',
'e262181e5298faaefbfcec1f6b3e5684b50a31ed0c751f052a725a6dfafed2a7',
'e5cc268ab1ddd6e650fb5bac1e8d2bee01d2e561674eec0198683757347ded3e'];
请注意,数组已经排序。这是排序代码,我希望这里不做任何事情:
var sortedArray = underscore.sortBy(stringsArray, function (s) { return s.toLowerCase().charCodeAt() * -1; }).reverse();
但是结果数组未排序:
[ '2b9ee0e611af977edbfd6bb04a56ebe05af07bdbc2daf88e5617fb872487f27c',
'6f009f9cb714849dba36a302d96dcd940c803bab5aa72dc25f52c26d2a32aab6',
'980942c275b7a407650980d6be561e6260edc55316247f20c3250ffc4d3d3c2f',
'e5cc268ab1ddd6e650fb5bac1e8d2bee01d2e561674eec0198683757347ded3e',
'e262181e5298faaefbfcec1f6b3e5684b50a31ed0c751f052a725a6dfafed2a7' ]
这很奇怪。在大多数情况下,我检查了代码是否有效。但是这次不是。怎么了为什么数组被打乱?您如何正确排序?
编辑:嗯,看起来我的代码只在第一个字符上排序。如果有人可以递归检查整个字符串,我将不胜感激。
答案 0 :(得分:0)
尚不清楚您是否真正想要对数组进行排序或是否要对其进行反向排序。如果您想对数组进行排序,则可以使用普通的javascript
var stringsArray =
['2b9ee0e611af977edbfd6bb04a56ebe05af07bdbc2daf88e5617fb872487f27c',
'6f009f9cb714849dba36a302d96dcd940c803bab5aa72dc25f52c26d2a32aab6',
'980942c275b7a407650980d6be561e6260edc55316247f20c3250ffc4d3d3c2f',
'e262181e5298faaefbfcec1f6b3e5684b50a31ed0c751f052a725a6dfafed2a7',
'e5cc268ab1ddd6e650fb5bac1e8d2bee01d2e561674eec0198683757347ded3e'];
stringsArray.sort()
["2b9ee0e611af977edbfd6bb04a56ebe05af07bdbc2daf88e5617fb872487f27c",
"6f009f9cb714849dba36a302d96dcd940c803bab5aa72dc25f52c26d2a32aab6",
"980942c275b7a407650980d6be561e6260edc55316247f20c3250ffc4d3d3c2f",
"e262181e5298faaefbfcec1f6b3e5684b50a31ed0c751f052a725a6dfafed2a7",
"e5cc268ab1ddd6e650fb5bac1e8d2bee01d2e561674eec0198683757347ded3e"]
如果要对数组进行反向排序,则可以对已排序的数组进行反向排序
stringsArray.sort().reverse()
["e5cc268ab1ddd6e650fb5bac1e8d2bee01d2e561674eec0198683757347ded3e",
"e262181e5298faaefbfcec1f6b3e5684b50a31ed0c751f052a725a6dfafed2a7",
"980942c275b7a407650980d6be561e6260edc55316247f20c3250ffc4d3d3c2f",
"6f009f9cb714849dba36a302d96dcd940c803bab5aa72dc25f52c26d2a32aab6",
"2b9ee0e611af977edbfd6bb04a56ebe05af07bdbc2daf88e5617fb872487f27c"]