[英]How to count words from window.prompt and sort them by number of apperance?
我需要計算提示中的單詞並將其寫入數組。 接下來,我必須計算它們的外觀並對其進行排序。 我有這樣的代碼:
let a = window.prompt("Write sentence") a = a.split(" ") console.log(a) var i = 0; for (let i = 0; i < a.length; i++) { a[i].toUpperCase; let res = a[i].replace(",", "").replace(".", "") var count = {}; a.forEach(function(i) { count[i] = (count[i] || 0) + 1; }); console.log(count); document.write(res + "<br>") }
我不知道如何將我的單詞與出現次數的特定數字聯系起來,並一次寫下這個單詞。 最后,它看起來應該像是:a =“這個句子,這個支架,這個句子,很好。” 這-3句-3贊-1
如果我沒有誤解您的要求,那么Array.prototype.reduce()
和Array.prototype.sort()
會為您解決問題。 想象一下,我從您的window.prompt()
獲得了示例字符串。
let string = `this constructor doesn't have neither a toString nor a valueOf. Both toString and valueOf are missing`; let array = string.split(' '); //console.log(array); let result = array.reduce((obj, word) => { ++obj[word] || (obj[word] = 1); // OR obj[word] = (++obj[word] || 1); return obj; }, {}); sorted_result = Object.keys(result).sort(function(a,b){return result[a]-result[b]}) console.log(result); console.log(sorted_result);
根據問題編輯
let string = `This sentence, this sentence, this sentence, nice.`; let array = string.split(' '); array = array.map(v => v.toLowerCase().replace(/[.,\\s]/g, '')) let result = array.reduce((obj, word) => { ++obj[word] || (obj[word] = 1); // OR obj[word] = (++obj[word] || 1); return obj; }, {}); console.log(result)
您可以使用reduce。 像這樣:
const wordsArray = [...].map(w => w.toLowerCase());
const wordsOcurrenceObj = wordsAray.reduce((acc, word) => {
if (!acc[word]) {
acc[word] = 0;
}
acc[word] += 1;
return acc;
}, {});
這樣做是為了跟蹤對象中的單詞。 當單詞不存在時,以零初始化。 然后,每次遇到該單詞時加1。 您最終將得到一個這樣的對象:
{
'word': 3,
'other': 1,
...
}
在計數的末尾添加另一個循環並打印它們:
for(let word in count) {
console.log(word + " appeared " + count[word] + " times");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.