在不排序的情況下計算陣列中唯一元素 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