基于唯一值计数的 JS 对象过滤器
Posted
技术标签:
【中文标题】基于唯一值计数的 JS 对象过滤器【英文标题】:JS Object filter based on count of unique values 【发布时间】:2022-01-22 17:03:35 【问题描述】:考虑以下示例 JS 对象
const samplejson = [
id:'1',value: "AC",,
id:'2',value: "AB",,
id:'3',value: "AC",,
id:'4',value: "AA",,
id:'5',value: "AA",,
id:'6',value: "AA",,
id:'7',value: "AB",,
id:'8',value: "AC",,
id:'9',value: "AA",,
id:'10',value: "AA",,
]
我想根据值的唯一计数和降序过滤 JS 对象,如下所示
基于值计数 AA - 5、AB - 2 和 AC - 3,但我需要输出为 AA,AC
在 react 或 JS 中如何实现呢?
【问题讨论】:
请注意不是 JSON,而是一个 JS 对象。我已经编辑了问题以反映这一点 【参考方案1】:您可以通过以下步骤找到您想要的结果:
-
统计数值。
按值/计数对的计数降序排列。
删除计数,只保留值。
const items = [
id: '1', value: "AC" ,
id: '2', value: "AB" ,
id: '3', value: "AC" ,
id: '4', value: "AA" ,
id: '5', value: "AA" ,
id: '6', value: "AA" ,
id: '7', value: "AB" ,
id: '8', value: "AC" ,
id: '9', value: "AA" ,
id: '10', value: "AA" ,
];
const tally = new Map();
for (const value of items)
if (!tally.has(value)) tally.set(value, 0);
tally.set(value, tally.get(value) + 1);
// displaying as object because Map instances show empty in the snippet log
console.log(Object.fromEntries(tally));
const results = Array.from(tally)
.sort(([,countA], [,countB]) => countB - countA)
.map(([value]) => value);
console.log(results);
【讨论】:
【参考方案2】:看看这个:
const data = [id:'1',value: "AC",,id:'2',value: "AB",,id:'3',value: "AC",, id:'4',value: "AA",,id:'5',value: "AA",,id:'6',value: "AA",,id:'7',value: "AB",, id:'8',value: "AC",,id:'9',value: "AA",,id:'10',value: "AA",,];
const result = Object.entries(
data.reduce((acc, value ) => ( ...acc, [value]: (acc[value] || 0) + 1 ), )
).sort((a1, a2) => a2[1] - a1[1])
.map(([key]) => key)
.join(',');
console.log(result);
【讨论】:
【参考方案3】:您可以遍历示例数据中的任何键并计算字典中值的每次出现。然后,您既可以打印字典以获取出现次数的列表,也可以仅打印一个值的出现次数。
const data = [
id:'1',value: "AC",,
id:'2',value: "AB",,
id:'3',value: "AC",,
id:'4',value: "AA",,
id:'5',value: "AA",,
id:'6',value: "AA",,
id:'7',value: "AB",,
id:'8',value: "AC",,
id:'9',value: "AA",,
id:'10',value: "AA",,
]
// make a dict to store and count occurrences
dict = ;
//iterate over every key in your data and keep count in dict
//(initializing it to 1 if it not exists yet)
for(let i = 0; i < data.length; i++)
value = data[i].value;
if(value in dict)
dict[value]++;
else
dict[value] = 1;
// here the amount of occurrences are know
console.log(dict);
amountOfAA = dict['AA'];
输出: AC:3,AB:2,AA:5 5
【讨论】:
以上是关于基于唯一值计数的 JS 对象过滤器的主要内容,如果未能解决你的问题,请参考以下文章