কম্পিউটার টিউটোরিয়াল

জাভাস্ক্রিপ্টে অ্যারেতে সর্বোচ্চ ঘটনা বা প্রথম নির্বাচিত মান বের করা

আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা একটি লিটেরেল ভ্যালুর অ্যারে নিবে। ফাংশনটি অ্যারেতে সর্বোচ্চ ঘটনাওয়ালা ভ্যালু রিটার্ন করবে, এবং যদি ঘটনা সমান হয় তবে সমান ঘটনাওয়ালা গুলোর মধ্যে প্রথম নির্বাচিত মানটি রিটার্ন করবে।

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
  1. জাভাস্ক্রিপ্ট Array.slice() মেথড

  2. জাভাস্ক্রিপ্ট array.values() মেথড

  3. জাভাস্ক্রিপ্ট array.flatMap() মেথড

  4. জাভাস্ক্রিপ্ট Array slice() মেথড