हमें एक JavaScript फ़ंक्शन लिखना है जो literals की एक सरणी लेता है जिसमें दोहराए जाने वाले मान होते हैं। हमारा फ़ंक्शन सरणी में सबसे सामान्य तत्व(तत्वों) की एक सरणी लौटाना चाहिए (यदि दो या अधिक तत्व समान संख्या में सबसे अधिक बार आते हैं तो सरणी में उन सभी तत्वों को शामिल करना चाहिए)।
उदाहरण
इसके लिए कोड होगा -
const arr1 = ["a", "c", "a", "b", "d", "e", "f"];
const arr2 = ["a", "c", "a", "c", "d", "e", "f"];
const getMostCommon = arr => {
const count = {};
let res = [];
arr.forEach(el => {
count[el] = (count[el] || 0) + 1;
});
res = Object.keys(count).reduce((acc, val, ind) => {
if (!ind || count[val] > count[acc[0]]) {
return [val];
};
if (count[val] === count[acc[0]]) {
acc.push(val);
};
return acc;
}, []);
return res;
}
console.log(getMostCommon(arr1));
console.log(getMostCommon(arr2));
आउटपुट
कंसोल में आउटपुट होगा -
[ 'a' ] [ 'a', 'c' ]