2016-03-29 18 views
-1

我想按降序排列數組,然後返回該數組的前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

嘗試反過來:'words.sort(...)切片(...) ' – georg

+0

'sort(function(a,b){ return b - a })'只適用於數字,沒有別的! – Bergi

+0

[不要將數組用於'words'](http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/)! – Bergi

回答

1

問題可能是因爲片是不可變的,你需要重新收集,你可以試試這個:

topwords = [].slice.call(topwords).sort(function(a, b){ 
    return b - a 
}); 
0

排序將數組排序,並與當前的更新。如果你想保留備份,你可以嘗試這樣的事:

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