我有一个包含重复值的数组,我从 API 获取这些值,下面的代码使用 ...new Set() 方法获取所有数学的注释,而没有重复的注释:< /p>
let notes = [];
if (props.getAllNotes()) {
const maths = props.getAllNotes().map(item => {
return item.subjects[0].math_note
});
notes = [...new Set(maths)];
}
这就是我在 props.getAllNotes() 中的内容:
notes = [15,16,10,13,15,16,10,18,11,13,15,16,10,18,11];
这就是我得到的:
notes = [15,16,10,13,18,11];
我想在最终数组 notes 中添加每个注释的计数,例如:
notes = [{10: 3}, {15: 5}...]
注释方法在对象中执行此操作,我需要对最终数组 notes 执行此操作,其中我使用 ...new Set() 方法,因为我我正在通过它进行映射以呈现一些数据
const counts = stars.reduce((acc, value) => ({
...acc,
[value]: (acc[value] || 0) + 1
}), {}); Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
创建包含每个数字的频率的对象后,您可以对其条目进行
map来创建所需的对象数组。let arr = [15,16,10,13,15,16,10,18,11,13,15,16,10,18,11]; let res = Object.entries(arr.reduce((acc, n) => { acc[n] = (acc[n] || 0) + 1; return acc; }, {})).map(([k, v]) => ({[k]: v})); console.log(res);