在不排序 JavaScript 的情况下计算数组中唯一元素的数量

javascriptweb developmentobject oriented programming更新于 2025/10/15 13:00:17

假设我们有一个包含一些重复值的文字数组 −

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

相关文章


有用资源