我需要根据单词数量以升序排列打印输入字符串。我试过这段代码!
我的问题是,如何根据
count
值对元素进行排序?即应首先显示较大的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 ]
答案 0 :(得分:2)
变化:
return count;
为:
return Object.keys(count).map(k => [k, count[k]])
.sort((a, b) => a[1] < b[1]).map(e => e[0]);
答案 1 :(得分:1)
您的count
变量是一个对象。虽然您将其定义为数组,但它不是真正的数组元素,而是字属性。所以你实际上正在排序一个空数组。
以下是如何调整代码以使其正常工作的方法:
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; }
答案 2 :(得分:1)
您可以按值对键进行排序。
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; }