কম্পিউটার

বস্তুর ফিল্টার অ্যারে যার বৈশিষ্ট্য জাভাস্ক্রিপ্টে একটি মান ধারণ করে


ধরুন, আমাদের কাছে এই ধরনের বস্তুর একটি অ্যারে আছে −

const arr = [{
   name: 'Paul',
   country: 'Canada',
}, {
   name: 'Lea',
   country: 'Italy',
}, {
   name: 'John',
   country: 'Italy',
}, ];

একটি স্ট্রিং কীওয়ার্ডের উপর নির্ভর করে আমাদের অবজেক্টের অ্যারে ফিল্টার করার একটি উপায় তৈরি করতে হবে। বস্তুর যেকোনো বৈশিষ্ট্যে অনুসন্ধান করতে হবে।

যেমন-

When we type "lea", we want to go through all the objects and all their properties to return the objects that contain "lea".
When we type "italy", we want to go through all the objects and all their properties to return the objects that contain italy.

উদাহরণ

এর জন্য কোড হবে −

const arr = [{
      name: 'Paul',
      country: 'Canada',
   }, {
      name: 'Lea',
      country: 'Italy',
   }, {
      name: 'John',
      country: 'Italy',
}, ];
const filterByValue = (arr = [], query = '') => {
   const reg = new RegExp(query,'i');
   return arr.filter((item)=>{
      let flag = false;
      for(prop in item){
         if(reg.test(item[prop])){
            flag = true;
         }
      };
      return flag;
   });
};
console.log(filterByValue(arr, 'ita'));

আউটপুট

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

[
   { name: 'Lea', country: 'Italy' },
   { name: 'John', country: 'Italy' }
]

  1. জাভাস্ক্রিপ্টে অবজেক্টের অ্যারের বৈশিষ্ট্যগুলি কীভাবে অ্যাক্সেস করবেন?

  2. জাভাস্ক্রিপ্ট - অ্যারে অবজেক্টের দৈর্ঘ্য

  3. 2টি বস্তুর তুলনা করার সময় গ্রুপিং অ্যারে নেস্টেড মান - জাভাস্ক্রিপ্ট

  4. জাভাস্ক্রিপ্টে একাধিক বৈশিষ্ট্য দ্বারা অবজেক্টের অ্যারে সাজান