计算数组中的唯一元素而不对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
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短