首页  >  问答  >  正文

使用 ...new Set 在 filtred 数组中添加计数重复值

我有一个包含重复值的数组,我从 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
}), {});

P粉186897465P粉186897465169 天前310

全部回复(1)我来回复

  • P粉770375450

    P粉7703754502024-04-05 17:54:48

    创建包含每个数字的频率的对象后,您可以对其条目进行 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);

    回复
    0
  • 取消回复