[英]How do I reduce a javascript string array to unique values but keep count of the number of duplicates?
I have an array with a number of strings, like this one:我有一个包含许多字符串的数组,比如这个:
["e", "e", "e", "e", "a", "e", "e", "a", "e", "e", "e", "e", "e", "o", "a", "e", "r", "e", "e", "e", "o", "e", "u"]
Now I want to reduce this array so it only contains unique strings.现在我想减少这个数组,所以它只包含唯一的字符串。 At the same time I want to keep count of the number of duplicates and (preferably) calculate a percentage that shows number of duplicates divided by the total number of strings.
同时,我想计算重复次数并(最好)计算一个百分比,该百分比显示重复次数除以字符串总数。
I'm thinking an end result that looks something like this:我在想一个看起来像这样的最终结果:
[
{
letter: "e",
duplicates: 16,
percentage: 0.695652173913043
},
{
letter: "a",
duplicates: 3,
percentage: 0.130434782608696
},
{
letter: "o",
duplicates: 2,
percentage: 0.08695652173913
},
{
letter: "r"
duplicates: 1,
percentage: 0.043478260869565
},
{
letter: "u",
duplicates: 1,
percentage: 0.043478260869565
}
]
How would I go about making this transformation in JavaScript/ES6?我将如何 go 在 JavaScript/ES6 中进行这种转换?
let array = ["e", "e", "e", "e", "a", "e", "e", "a", "e", "e", "e", "e", "e", "o", "a", "e", "r", "e", "e", "e", "o", "e", "u"] let result = [...new Set(array)].map(e =>({letter:e, duplicates:array.filter(n => n===e).length, percentage:array.filter(n => n===e).length/array.length})) console.log(result)
This is possible by using Array#from , Array#reduce , Map , Array#map , and destructuring .这可以通过使用Array#from 、 Array#reduce 、 Map 、 Array#map和destructuring来实现。
The reduce allows to regroup and count letters and their occurrence. reduce 允许重新组合和计算字母及其出现次数。 Once they've been organized properly you can then proceed to map through all the results and calculate the percentage.
一旦它们被正确组织,您就可以通过所有结果继续 map 并计算百分比。
const data = ["e", "e", "e", "e", "a", "e", "e", "a", "e", "e", "e", "e", "e", "o", "a", "e", "r", "e", "e", "e", "o", "e", "u"]; const res = Array.from(data.reduce((acc, cur) => acc.set(cur, (acc.get(cur)||0) + 1), new Map())).map(([letter, duplicates]) => ({letter, duplicates, percentage: duplicates / data.length})); console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.