我正在使用一个函数来计算数组中字符串的重复数,并显示每个字符串出现的次数。问题是它在任何旧函数中吐出它们。输出如下:
来了 - > 22次堕胎来临 - >约1次来 - > 3 时间确认来了 - >实际上来了1次 - > 2次 事务来了 - > 1次前来 - >援助来了1次 - > 1次 一切都来了 - >允许4次来 - > 1次盟友来了 - > 1次 几乎来了 - >单独来1次 - > 1次已经来了 - > 1 时代也来了 - >总共会来2次 - > 1次美国来了 - > 1次美国人来了 - > 1次美国人来了 - > 2次来 - > 3次类比来了 - > 1次来 - > 46次 另一个来了 - > 4月1次到来 - > 1次到来 - > 16 时区来了 - > 1次
我需要做的是将这些输出放到另一个数组中,然后对它们进行排序,以便我可以迭代它并使输出看起来像:
'a'来了997次'和'来了439次'你好'来了398次'highboy' 得到147次“优秀”99次'大规模'44次'纵火'30次 '珍妮'来了19次'紫色'来了6次
......等等。
这是我正在使用的功能:
function count() {
var words = ['hi', 'hi', 'hello', 'smack'];
words.sort();
var current = null;
var cnt = 0;
for (var i = 0; i < words.length; i++) {
if (words[i] != current) {
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times<br>');
}
current = words[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times');
}
}
count();
我不想通过调用count()并拥有一堆document.write()
来使用它,我想将它全部打包到另一个数组中,我可以按顺序获取所有这些值。我希望这是有道理的。
我知道我必须创建另一个数组,比如var sorted_array
;但是如何才能获得该数据的信息呢?
答案 0 :(得分:1)
一种方式是这样的(避免多个document.write)
function count() {
var words = ['hi', 'hi', 'hello', 'smack'];
words.sort();
var current = null;
var cnt = 0;
var output = [];
for (var i = 0; i < words.length; i++) {
if (words[i] != current) {
if (cnt > 0) {
output.push(current + ' comes --> ' + cnt + ' times<br />');
}
current = words[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
output.push(current + ' comes --> ' + cnt + ' times<br />');
output.sort(); // sort by word, not by how many occurrences of a word
document.write(output.join());
/*alert(output);*/
}
}
count();
答案 1 :(得分:1)
将问题分成两部分,首先创建一个包含重复项及其计数的数据结构,然后将此数据结构转换为按出现次数排序的数组。然后你可以用结果做任何你需要的事。
var occurences = ['hi', 'hi', 'hello', 'smack', 'smack', 'smack'].reduce(function (res, word) {
res[word] = (res[word] || 0) + 1
return res;
}, {});
var duplicates = Object.keys(occurences).map(function (k) {
return {word: k, count: occurences[k]};
})
//make sure that we only keep duplicates
.filter(function(item) { return item.count > 1; })
//sort them by count descendent
.sort(function (a, b) { return b.count - a.count; })
//display the words and their count in the console
.forEach(function (dup) { console.log(dup.word, dup.count); });
答案 2 :(得分:0)
我会使用单词作为键创建一个对象,并将计数作为值,然后您可以输出它,无论如何:
function count(words) {
var o = {}, a= [];
for (var i=0; i<words.length; i++)
o[words[i]] = words[i] in o ? o[words[i]]+1 : 1;
for (var key in o)
a.push(key + ' comes --> ' + o[key] + ' times<br>');
return a.sort().join('');
}
答案 3 :(得分:0)
为你做了fiddle,希望这有帮助。
var words = ['foo', 'bar', 'foo', 'baz'],
word,
key,
wordCount = {},
sortedWordCountKeys,
pluralize,
output;
for (word in words) {
wordCount[words[word]] = wordCount[words[word]] ?
wordCount[words[word]] + 1 :
1;
}
sortedWordCountKeys = Object.keys(wordCount).sort(function(a, b) {
return wordCount[b] - wordCount[a];
});
for (key in sortedWordCountKeys) {
word = sortedWordCountKeys[key];
pluralize = wordCount[word] > 1 ? 's' : '';
output = wordCount[word] + ' occurence' + pluralize + ' of "' + word + '" found.';
console.log(output);
}
或许你更喜欢这个fiddle
var words = ['foo', 'bar', 'foo', 'baz'],
i,
word,
wordCount = {},
sortedWordCountKeys,
pluralize,
output;
for (i = 0; i < words.length; i++) {
wordCount[words[i]] = wordCount[words[i]] ?
wordCount[words[i]] + 1 :
1;
}
sortedWordCountKeys = Object.keys(wordCount).sort(function(a, b) {
return wordCount[b] - wordCount[a];
});
for (i = 0; i < sortedWordCountKeys.length; i++) {
word = sortedWordCountKeys[i];
pluralize = wordCount[word] > 1 ? 's' : '';
output = wordCount[word] + ' occurence' + pluralize + ' of "' + word + '" found.';
console.log(output);
}
或者甚至可能是fiddle
var text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel lacus justo. Quisque eu lorem at metus condimentum iaculis a a risus. Proin vitae ligula iaculis, vehicula ligula quis, luctus ipsum. Nulla consectetur eros in nisi tempus, sit amet mollis eros accumsan. Duis dignissim ornare magna, vel elementum arcu accumsan ut. Curabitur at ligula a dui pretium placerat at eu nisi. Donec a tellus tempor, venenatis tortor nec, auctor nisi. Sed congue arcu sit amet tortor vulputate vulputate. Etiam sed odio eleifend, rhoncus risus nec, porttitor libero. Etiam placerat mauris vitae felis egestas, in tristique velit condimentum. Nam odio elit, congue eget semper vel, lacinia vel dolor. Duis tempor enim diam, vel auctor tortor tincidunt eget. Praesent congue quam mi, et lobortis ipsum tempus nec. Duis blandit mi et facilisis adipiscing. Etiam ut tellus ut dolor convallis consectetur a id nulla.',
i,
words = text.split(' '),
word,
wordCount = {},
sortedWordCountKeys,
pluralize,
output;
for (i = 0; i < words.length; i++) {
words[i] = words[i]
.replace(/\./g, '')
.replace(/\,/g, '');
wordCount[words[i]] = wordCount[words[i]] ?
wordCount[words[i]] + 1 :
1;
}
sortedWordCountKeys = Object.keys(wordCount).sort(function(a, b) {
return wordCount[b] - wordCount[a];
});
for (i = 0; i < sortedWordCountKeys.length; i++) {
word = sortedWordCountKeys[i];
pluralize = wordCount[word] > 1 ? 's' : '';
output = wordCount[word] + ' occurence' + pluralize + ' of "' + word + '" found.';
console.log(output);
}