计算数组中的唯一元素而不对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 儿子31岁祝福语简短
16 前程祝福语简短暖心
17 中秋祝福语简短版大全
18 住学长学姐祝福语简短