मान लीजिए हमारे पास लिटरल की एक सरणी है जिसमें कुछ डुप्लिकेट मान हैं:
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