কম্পিউটার

অ্যারের জাভাস্ক্রিপ্টের সামনে শেষ প্রদত্ত সংখ্যক উপাদান স্থানান্তর করুন


ধরা যাক, আমাদের একটি অ্যারে ফাংশন লিখতে হবে, বলুন prependN() যেটি একটি সংখ্যা নেয় n (n <=ফাংশনের সাথে ব্যবহৃত অ্যারের দৈর্ঘ্য) এবং এটি শেষ থেকে n উপাদান নেয় এবং অ্যারের সামনে রাখে।

আমাদের এটি ঠিক জায়গায় করতে হবে এবং কার্যটির সফল সমাপ্তি বা ব্যর্থতার উপর ভিত্তি করে ফাংশনটি শুধুমাত্র একটি বুলিয়ান প্রদান করবে৷

যেমন −

// if the input array is:
const arr = ["blue", "red", "green", "orange", "yellow", "magenta",
"cyan"];
// and the number n is 3,
// then the array should be reshuffled like:
const output = ["yellow", "magenta", "cyan", "blue", "red", "green",
"orange"];
// and the return value of function should be true

এখন, এই ফাংশনের জন্য কোড লিখি -

উদাহরণ

const arr = ["blue", "red", "green", "orange", "yellow", "magenta",
"cyan"];
Array.prototype.reshuffle = function(num){
const { length: len } = this;
   if(num > len){
      return false;
   };
   const deleted = this.splice(len - num, num);
   this.unshift(...deleted);
   return true;
};
console.log(arr.reshuffle(4));
console.log(arr);

আউটপুট

কনসোলে আউটপুট হবে −

true
[
   'orange', 'yellow',
   'magenta', 'cyan',
   'blue', 'red',
   'green'
]

  1. জাভাস্ক্রিপ্টে একটি নির্দিষ্ট ট্যাগের উপাদানের সংখ্যা?

  2. একটি জাভাস্ক্রিপ্ট অ্যারে প্রথম উপাদান এবং শেষ উপাদান?

  3. জাভাস্ক্রিপ্ট অ্যারে শিফট()

  4. জাভাস্ক্রিপ্টে অ্যারে শিফট()