สมมติว่าเรามีอาร์เรย์ของลิเทอรัลที่มีค่าซ้ำบ้าง:
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