gpt4 book ai didi

javascript - Lodash:将具有重复值的数组转换为具有重复出现次数的对象

转载 作者:行者123 更新时间:2023-11-30 08:30:07 25 4
gpt4 key购买 nike

这是我的数组:

['California','Texas','Texas','Texas','New York','Missouri','New Mexico','California']

lodash 中有没有一种方法可以将其转换为具有重复出现次数的对象,如下所示:

[
{'name':'California', 'count':2},
{'name':'Texas', 'count':3},
{'name':'New York', 'count':1},
{'name':'Missouri', 'count':1},
{'name':'New Mexico', 'count':1},
]

我尝试了很多组合,但都没有成功。文档:https://lodash.com/docs#countBy

最佳答案

您可以只映射 _.countBy 的结果。

var array = ['California','Texas','Texas','Texas','New York','Missouri','New Mexico','California'],
count = _.countBy(array),
result = _.map(count, (v, k) => ({ name: k, count: v }));

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

结合_.chain

var array = ['California','Texas','Texas','Texas','New York','Missouri','New Mexico','California'],
count = _
.chain(array)
.countBy()
.map((v, k) => ({ name: k, count: v }));

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

关于javascript - Lodash:将具有重复值的数组转换为具有重复出现次数的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39232341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com