簡體   English   中英

當數字是每個條目的第一部分時,如何在Javascript中對數組進行數字排序?

[英]How can I numerically sort an array in Javascript when the number is the first part of each entry?

我正在從字符串創建單詞列表。 然后,我將該字符串分成單個單詞,收集每個單詞重復多少次的計數,然后顯示出來。 那里的一切都完美運行。 但是,結果顯示的單詞和計數沒有特定的順序。 我想先顯示最高的數字。 我生成了以下代碼:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display the array values after the split.</p>

<button onclick="analyze()">Analyze</button>

<p id="displayText"></p>

<script>
function analyze() {
    var str = "This this is is is is is is is is is is is is is is is just just a test test test";
    var res = str.split(" ");
    document.getElementById("displayText").innerHTML = res;
    document.getElementById("displayText").innerHTML += "<br/><br/>The amount of words is: " + res.length + "<br/><br/><br/>";

    document.getElementById("displayText").innerHTML += "The list of words:<br/><br/>";

    var words = [];

    var wordsWithCount = [];

    for (i = 0; i < res.length; i++) {
        words.push(res[i]);
        document.getElementById("displayText").innerHTML += words[i] + "<br/><br/>";
    }

    var current = null;
    var cnt = 0;
    for (var i = 0; i < words.length; i++) {
        if (words[i] != current) {
            if (cnt > 0) {
                document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>";
                wordsWithCount.push(cnt + " - " + current);
            }
            current = words[i];
            cnt = 1;
        } else {
            cnt++;
        }
    }

    if (cnt > 0) {
        document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>";
        wordsWithCount.push(cnt + " - " + current);
    }

    wordsWithCount.sort();

    document.getElementById("displayText").innerHTML += "<br/><br/><br/><br/><br/>The list of SORTED words:<br/><br/>";

    for (i = 0; i < wordsWithCount.length; i++) {
        document.getElementById("displayText").innerHTML += wordsWithCount[i] + "<br/><br/>";
    }
}
</script>

</body>
</html>

這是輸出的最后一位。 如您所見,它正在排序,但僅按第一位。 因此,在2之前顯示15。

已排序單詞列表:

1-這個

1-一個

1-這個

15-是

2-剛好

3-測試

在某個時候,我很可能需要將其分成兩個數組,因為我希望用戶能夠復制並粘貼所有單詞,而沒有數字。 但是,我認為這將是最后一步,因為如果我將每個單詞的頻率分解成它自己的數字數組,並將單詞保留在它們自己的數組中,則sort函數將對一個數組進行排序,而對另一個數組進行排序數組將不跟隨。

使用Intl.Collator做到這Intl.Collator 像這樣:

var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
var test = ['1 - this', '3 - this', '14 - this'];
test.sort(collator.compare);

輸出["1 - this", "3 - this", "14 - this"]

 var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'}); var test = ['1 - this', '3 - this', '14 - this']; console.log(test.sort(collator.compare)); 

使用parseInt()方法和此處找到的解決方案( 如何正確地對整數數組進行排序 )可以有效地進行混合!

替換wordsWithCount.sort(); 與:

function sortNumber(a,b) {
      return parseInt(a) - parseInt(b);
}

wordsWithCount.sort(sortNumber);

住在這里: https : //www.w3schools.com/code/tryit.asp?filename=FFGXRIN0VZWO

您可以只添加一個自定義的比較函數,以傳遞到您的wordsWithCount.sort()調用中。 在此,我宣布一個調用的函數compareWordCount@Pointy使用的sugfested方法; 使用parseInt忽略附加到數組值的所有非整數部分。 看一下這個工作片段:

 <!DOCTYPE html> <html> <body> <p>Click the button to display the array values after the split.</p> <button onclick="analyze()">Analyze</button> <p id="displayText"></p> <script> function compareWordCount(a,b) { if (parseInt(a) < parseInt(b)) return -1; return 1; } function analyze() { var str = "This this is is is is is is is is is is is is is is is just just a test test test"; var res = str.split(" "); document.getElementById("displayText").innerHTML = res; document.getElementById("displayText").innerHTML += "<br/><br/>The amount of words is: " + res.length + "<br/><br/><br/>"; document.getElementById("displayText").innerHTML += "The list of words:<br/><br/>"; var words = []; var wordsWithCount = []; for (i = 0; i < res.length; i++) { words.push(res[i]); document.getElementById("displayText").innerHTML += words[i] + "<br/><br/>"; } var current = null; var cnt = 0; for (var i = 0; i < words.length; i++) { if (words[i] != current) { if (cnt > 0) { document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>"; wordsWithCount.push(cnt + " - " + current); } current = words[i]; cnt = 1; } else { cnt++; } } if (cnt > 0) { document.getElementById("displayText").innerHTML += "<br/><br/>" + cnt + " - " + current + "<br/>"; wordsWithCount.push(cnt + " - " + current); } wordsWithCount.sort(compareWordCount); document.getElementById("displayText").innerHTML += "<br/><br/><br/><br/><br/>The list of SORTED words:<br/><br/>"; for (i = 0; i < wordsWithCount.length; i++) { document.getElementById("displayText").innerHTML += wordsWithCount[i] + "<br/><br/>"; } } </script> </body> </html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM