在不排序的情況下計算陣列中唯一元素 JavaScript


假設我們有一個包含某些重複值的面值陣列 -

const arr = ['Cat', 'Dog', 'Cat', 'Elephant', 'Dog', 'Grapes', 'Dog', 'Lion', 'Grapes', 'Lion'];

我們需要編寫一個返回陣列中唯一元素數量的函式。將使用 Array.prototype.reduce() 和 Array.prototype.lastIndexOf() 進行此操作 -

示例

const arr = ['Cat', 'Dog', 'Cat', 'Elephant', 'Dog', 'Grapes', 'Dog',
'Lion', 'Grapes', 'Lion'];
const countUnique = arr => {
   return arr.reduce((acc, val, ind, array) => {
      if(array.lastIndexOf(val) === ind){
         return ++acc;
      };
      return acc;
   }, 0);
};
console.log(countUnique(arr));

輸出

控制檯中的輸出將為 -

5

更新於:2020 年 8 月 26 日

277 次瀏覽

啟動你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.