हमें एक JavaScript फ़ंक्शन लिखना आवश्यक है जो लिटरल मानों की एक सरणी लेता है। हमारा फ़ंक्शन तब सरणी मान की उच्चतम घटना वापस करना चाहिए, और यदि समान घटना है, तो हमें समान घटनाओं के पहले चयनित मान को वापस करना चाहिए।
const arr = ['25', '50', 'a', 'a', 'b', 'c']
इस मामले में, हमें 'a' वापस करना चाहिए
const arr = ['75', '100', 'a', 'b', 'b', 'a']
इस मामले में, मुझे 'a' भी मिलना चाहिए
उदाहरण
इसके लिए कोड होगा −
const arr = ['25', '50', 'a', 'a', 'b', 'c']; const arr1 = ['75', '100', 'a', 'b', 'b', 'a']; const getMostFrequentValue = (arr = []) => { let count = 0, ind = -1; arr.forEach((el, i) => { this[el] = this[el] || { count: 0, ind: i }; this[el].count++; if (this[el].count > count) { count = this[el].count; ind = this[el].ind; return; }; if (this[el].count === count && this[el].ind < ind) { ind = this[el].ind; }; }, Object.create(null)); return arr[ind]; }; console.log(getMostFrequentValue(arr)); console.log(getMostFrequentValue(arr1));आउटपुट
और कंसोल में आउटपुट होगा −
a a