【发布时间】:2018-02-01 04:22:50
【问题描述】:
我正在尝试获取一个段落并将其转换为单词并实现每个单词的频率。
var pattern = /\w+/g,
string = "mahan mahan mahan yes yes no",
matchedWords = string.match(pattern);
/* The Array.prototype.reduce method assists us in producing a single value from an
array. In this case, we're going to use it to output an object with results. */
var counts = matchedWords.reduce(function(stats, word) {
/* `stats` is the object that we'll be building up over time.
`word` is each individual entry in the `matchedWords` array */
if (stats.hasOwnProperty(word)) {
/* `stats` already has an entry for the current `word`.
As a result, let's increment the count for that `word`. */
stats[word] = stats[word] + 1;
} else {
/* `stats` does not yet have an entry for the current `word`.
As a result, let's add a new entry, and set count to 1. */
stats[word] = 1;
}
/* Because we are building up `stats` over numerous iterations,
we need to return it for the next pass to modify it. */
return stats;
}, {})
var dict = []; // create an empty array
// this for loop makes a dictionary for you
for (i in counts) {
dict.push({
'text': i
});
dict.push({
'size': counts[i]
});
};
/* lets print and see if you can solve your problem */
console.log(dict);
dict 变量返回:
[ { text: 'mahan' },{ size: 3 },{ text: 'yes' },{ size: 2 },{ text:'no'},{ size: 1 } ]
但我使用的是数据可视化代码,我需要将结果变成这样的:
[ { "text": "mahan" , "size": 3 },{ "text: "yes", size: 2 },{ "text":'no', "size": 1 } ]
我知道这是基本的,但我只是一个试图为项目使用一些代码的艺术家。感谢您的帮助。
【问题讨论】:
-
那么不要使用两个单独的对象:
push({text:i,size:counts[i]})
标签: javascript arrays string object properties