ট্র্যাক
/
JavaScript
JavaScript
/
সিলেবাস
/
অ্যারে বিশ্লেষণ
অ্

অ্যারে বিশ্লেষণ মধ্যে JavaScript

14টি অনুশীলনী

অ্যারে বিশ্লেষণ সম্পর্কে

JavaScript-এ Array-এর ইনস্ট্যান্সগুলো সাধারণ অবজেক্ট, যেগুলোতে অনেক দরকারি মেথড যোগ করা হয়েছে। এতে length প্রপার্টি ছাড়াও অ্যারে ট্রাভার্স করা, বিশ্লেষণ করা আর পরিবর্তন করার মেথড থাকে। অ্যারের এলিমেন্টগুলো ওই অ্যারের ইনডেক্সড প্রপার্টি। ওই ইনডেক্সড প্রপার্টিগুলোর উপর নিজে হাতে ইটারেট করার বদলে অ্যারে অ্যানালাইসিস ব্যবহার করুন। অ্যারের কনটেন্ট বিশ্লেষণ করে এমন অনেক বিল্ট-ইন ফাংশন আর্গুমেন্ট হিসেবে এমন একটি ফাংশন নেয়, যা ট্রু বা ফলস রিটার্ন করে। এমন ফাংশনকে বলা হয় predicate।

সাধারণভাবে, অ্যাবস্ট্রাকশন বা বিল্ট-ইন মেথড ব্যবহার করা for বা .forEach দিয়ে একই কাজ করার চেয়ে বেশি স্বাভাবিক, পড়তে সহজ আর রক্ষণাবেক্ষণযোগ্য।

const values = [1, 2, 5, 8, 8, 10];

// Array#some stops iteration as soon as the given predicate returns true; it
// returns false if none of the elements in the array pass the predicate. In
// other words: return true if for some item the given function returns true.
//
const isOdd = (item) => item % 2 === 1;
const areSomeOdd = values.some(isOdd);
// => true

// Array#every stops iteration as soon as the given predicate returns false; it
// returns true if each and every element passes the predicate. In other words:
// return true if for every item the given function returns true
//
const areAllPositive = values.every((item) => item >= 0);
// => true

// Most array analysis predicates get more than one argument as their input. In
// most cases it will be:
//
// 1. item:  the current element being evaluated
// 2. index: the index associated with that element
// 3. self:  the array itself
//
// Since Array#indexOf(value) returns the first index of value in the array, it
// can be used to determine if a particular (item, index) pair does NOT match
// the first occurrence of the item. Only for the first occurrence, the index
// of the item will match the passed in index.
//
//   ['a', 'b', 'a'].indexOf('a')
//   // => 0
//
//   isDuplicate('a', 0, ['a', 'b', 'a'])
//   // => false
//   isDuplicate('b', 1, ['a', 'b', 'a'])
//   // => false
//   isDuplicate('a', 2, ['a', 'b', 'a'])
//   // => true
//
function isDuplicate(item, index, self) {
  return self.indexOf(item) !== index;
}

const indexOfFirstDuplicate = values.findIndex(isDuplicate);
// => 4

// Some of the analysis functions don't take a predicate but instead take a
// value directly.
//
// Array#includes is the same as the more verbose options:
//
//   values.some((item) => item === 42)
//   values.indexOf(42) !== -1
//
// Array#indexOf is the same as the more verbose option:
//
//   values.findIndex((item) => item === 42) !== 1
//
const hasValue42 = values.includes(42);
// => false
GitHub-এর মাধ্যমে সম্পাদনা করুন লিংকটি নতুন একটি উইন্ডো বা ট্যাবে খুলবে

অ্যারে বিশ্লেষণ শিখুন