搜尋

首頁  >  問答  >  主體

使用 ...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粉186897465314 天前510

全部回覆(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
  • 取消回覆