JavaScript-এ অ্যারের মাঝপথে এলিমেন্ট যোগ করার বিল্ট-ইন সরাসরি মেথড নেই, কিন্তু splice() ব্যবহার করে সহজে করা যায়।
পদ্ধতি ১: splice() ব্যবহার (সুপারিশ করা)
splice(index, deleteCount, item1, item2, ...) - নির্দিষ্ট ইনডেক্সে এলিমেন্ট যোগ করতে deleteCount ০ রাখুন।
var months = ['Jan', 'March', 'April', 'June']; months.splice(1, 0, 'Feb'); // ইনডেক্স ১-এ ০টি মুছে 'Feb' যোগ console.log(months); // ['Jan', 'Feb', 'March', 'April', 'June']
পদ্ধতি ২: Custom insert() মেথড (Array.prototype-এ যোগ)
বারবার ব্যবহারের জন্য প্রোটোটাইপে মেথড যোগ করা যায়:
Array.prototype.insert = function(data, position) {
if (position >= this.length) {
this.push(data); // শেষে যোগ
} else if (position <= 0) {
this.unshift(data); // শুরুতে যোগ
} else {
// এলিমেন্টগুলো ডানদিকে শিফট
for (let i = this.length; i >= position; i--) {
this[i] = this[i - 1];
}
this[position] = data;
}
};
let arr = [1, 2, 3, 4];
arr.insert(-1, 2);
console.log(arr); // [1, 2, -1, 3, 4]
সাবধানতা
Array.prototype-এ মেথড যোগ করা সাধারণত পরামর্শ দিয়ে দেওয়া হয় না, কারণ এটি লাইব্রেরি বা ভবিষ্যতের JavaScript ভার্সনের সাথে দ্বন্দ্ব সৃষ্টি করতে পারে। বরং একটি ইউটিলিটি ফাংশন বা মডিউল ব্যবহার করুন।
আধুনিক পদ্ধতি (ES6+)
// স্প্রেড অপারেটর ব্যবহার করে (নতুন অ্যারে তৈরি) const insertAt = (arr, index, ...items) => [ ...arr.slice(0, index), ...items, ...arr.slice(index) ]; let nums = [1, 2, 4, 5]; nums = insertAt(nums, 2, 3); console.log(nums); // [1, 2, 3, 4, 5]