計數 JavaScript 陣列元素的出現次數並將其放入新的二維陣列中


我們需要編寫一個 JavaScript 函式,它接受一個文字值陣列。該函式隨後應該計算輸入陣列中每個元素的頻率,並在此基礎上準備一個新陣列。

例如 − 如果輸入陣列是 −

const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];

那麼輸出應該是 −

const output = [
   [5, 3],
   [2, 5],
   [9, 1],
   [4, 1]
];

示例

對應的程式碼如下 −

const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
const frequencyArray = (arr = []) => {
   const res = [];
   arr.forEach(el => {
      if (!this[el]) {
         this[el] = [el, 0];
         res.push(this[el])
      };
      this[el][1] ++
   }, {});
   return res;
};
console.log(frequencyArray(arr));

輸出

而控制檯中的輸出將是 −

[ [ 5, 3 ], [ 2, 5 ], [ 9, 1 ], [ 4, 1 ] ]

更新於: 2020 年 11 月 24 日

357 次瀏覽

開啟你的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.