使用Lodash计算字符串在数组中重复的次数

时间:2018-01-17 06:45:11

标签: javascript arrays lodash

我有一个字符串数组,这些字符串是来自数据库的博客文章的标签。

这是查询的示例最终结果:

["apple","banana", "apple", "orange","grapes","mango","banana"];

我需要知道在该数组中重复一次字符串的次数,以便我可以构建一种标记云。

最终结果应如下所示:[{name:"apple",count:2}, {name:"banana", count:2}, {name: "orange",count:1} ...];

我在我的项目中使用lodash,并希望尽可能使用它。普通的javascript也没关系。

4 个答案:

答案 0 :(得分:3)

您可以使用groupBy进行繁重的工作,然后根据自己的喜好使用地图格式化结果:



const data = ["apple", "banana", "apple", "orange", "grapes", "mango", "banana"];

const result = _.values(_.groupBy(data)).map(d => ({name: d[0], count: d.length}));

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用reducemap

var input = ["apple","banana", "apple", "orange","grapes","mango","banana"];

var map = input.reduce( (a,c) => ( a[c] = a[c] || 0, a[c]++, a ) ,{});

var output = Object.keys( map ).map( s => ({name: s, count:map[s]}) );

<强>演示

&#13;
&#13;
var input = ["apple", "banana", "apple", "orange", "grapes", "mango", "banana"];

var map = input.reduce((a, c) => (a[c] = a[c] || 0, a[c]++, a), {});

var output = Object.keys(map).map(s => ({
  name: s,
  count: map[s]
}));

console.log(output);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

创建地图,将地图名称映射到计数。循环遍历列表,对于每个项目,如果它在地图中,增加它的计数,否则将其计数设置为1。

if (tag in map) { map[tag] += 1 }
else { map[tag] = 1 }

然后你可以迭代地图并将其转换为对象列表。

答案 3 :(得分:0)

要计算使用_.countBy(),然后使用_.entries()转换为请求的表单,并将元组映射到对象:

const data = ["apple", "banana", "apple", "orange", "grapes", "mango", "banana"];

const result = _.entries(_.countBy(data)).map(([name, count]) => ({ name, count }));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>