2016-03-29 6 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

'ソート(関数(a、b){ リターン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

ソート配列をソートし、現在1でそれを更新します。他の方法でラウンドそれを試して

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