在不排序的情况下计算数组中唯一元素 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP