আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা লিটারেলগুলির একটি অ্যারে গ্রহণ করবে যাতে পুনরাবৃত্ত মান থাকে। আমাদের ফাংশনটি অ্যারেতে সবচেয়ে সাধারণ উপাদান(গুলা) রিটার্ন করবে (যদি দুটি বা ততোধিক উপাদান একই সংখ্যকবার সর্বোচ্চ হয় তবে সেগুলা সব অ্যারেতে থাকবে)।
উদাহরণ
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']