如何根据计数值对单词进行sorting:javascript

我需要根据单词数以升序打印inputstring。
我试过这段代码!

我的问题是 ,如何根据count数值对元素进行sorting? 即应该先显示更大的count数值字( count数值的降序)?

Javascript文件, app.js

 var x = stringCount("this is my file teting the things apple teting this is my the is is is is ", ' '); console.log(x); function stringCount(haystack, needle) { if (!needle || !haystack) { return false; } else { var words = haystack.split(needle), count = []; for (var i = 0, len = words.length; i < len; i++) { if (count.hasOwnProperty(words[i])) { count[words[i]] = parseInt(count[words[i]], 10) + 1; } else { count[words[i]] = 1; } } count.sort(); return count; } } 

这是我得到的输出

 [ this: 2, is: 6, my: 2, file: 1, teting: 2, the: 2, things: 1, apple: 1, '': 1 ] 

更改:

  return count; 

至:

  return Object.keys(count).map(k => [k, count[k]]) .sort((a, b) => a[1] < b[1]).map(e => e[0]); 

您可以按值sorting键。

 function stringCount(haystack, needle) { if (!needle || !haystack) { return false; } var words = haystack.split(needle), count = {}; words.forEach(function (a) { count[a] = (count[a] || 0) + 1; }); return count; } var x = stringCount("this is my file teting the things apple teting this is my the is is is is ", ' '); console.log(x); console.log(Object.keys(x).sort(function (a, b) { return x[b] - x[a]; })); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

您的countvariables是一个对象。 虽然你将它定义为一个数组,但它并不是真正的数组元素,而是字属性。 所以你实际上是sorting一个空的数组。

这里是你如何适应你的代码,使其工作:

 var x = stringCount("this is my file teting the things apple teting this is my the is is is is ", ' '); console.log(x); function stringCount(haystack, needle) { if (!needle || !haystack) { return false; } else { var words = haystack.split(needle).filter(x => x), // filter out empty words count = {}; // not an array for (var i = 0, len = words.length; i < len; i++) { if (count.hasOwnProperty(words[i])) { count[words[i]] = parseInt(count[words[i]], 10) + 1; } else { count[words[i]] = 1; } } return Object.keys(count) // array of words .sort( (a,b) => count[b] - count[a] ); // sort by count } } 
 .as-console-wrapper { max-height: 100% !important; top: 0; }