我试图按降序对数组进行排序,然后返回该数组的前20个元素。下面的代码是为了这样设计的,但问题出现了,当调用[].slice.call(topwords).sort(function(a, b){ return b - a});
时,数组不按降序排序。通过node-debug
运行代码时,我可以看到填充了topwords,并按原样填充:
"": 19
0-0: 1
1-0: 2
1-0.: 1
1-1: 1
2: 1
2/3: 1
2pm: 1
3-0: 3
3-1: 1
4: 1
4-0: 2
11am: 1
15: 1
16: 1
19:45: 1
28: 1
30: 1
30%: 2
// more of the same ...
我不确定为什么这个数组无法排序,然后整个元素被推到toptwenty才能显示出来?
CODE:
// function for getting the frequency of each word within a string
function getFreqword(){
var string = tweettxt.toString(), // turn the array into a string
changedString = string.replace(/,/g, " "), // remove the array elements
split = changedString.split(" "), // split the string
words = []; // array for the words
for (var i=0; i<split.length; i++){
if(words[split[i]]===undefined){
words[split[i]]=1;
} else {
words[split[i]]++;
}
}
return words;
}
// function for returning the top 20 words from getFreqword()
function getTopwords(){
var topwords = getFreqword(),
toptwenty = [];
[].slice.call(topwords).sort(function(a, b){
return b - a
});
if ( topwords.length < 20 ){
topwords = toptwenty;
return toptwenty;
} else {
for (var i=0; i<20; i++){
toptwenty.push(topwords[i]); // push the first 20 elements in topusers to the topten array
}
return toptwenty;
}
}
编辑:
[ undefined,
undefined,
1,
undefined,
1,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
1,
1,
undefined,
undefined,
undefined ]
运行代码时返回的内容。
答案 0 :(得分:1)
问题可能是因为切片是不可变的,你需要再次收集,你可以试试这个:
topwords = [].slice.call(topwords).sort(function(a, b){
return b - a
});
答案 1 :(得分:0)
Sort将对数组进行排序并使用当前数组进行更新。如果你想保留备份,你可以尝试这样的事情:
var arr = ["foo", "hello", "world", "test", "abc"];
var b = arr.slice().sort(function(a, b) {
return a < b ? -1: a > b ? 1 : 0;
});
print(arr)
print(b)
function print(obj) {
document.write("<pre>" + JSON.stringify(obj, 0, 4) + "</pre>");
}