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

জাভাস্ক্রিপ্টে অবজেক্ট গ্রুপ বাই প্রপার্টি


সমস্যা বিবরণ

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

ইনপুট:

const arr = [
  {food: 'apple', type: 'fruit'},
  {food: 'potato', type: 'vegetable'},
  {food: 'banana', type: 'fruit'},
];

আউটপুট:

[
  { type: 'fruit', foods: ['apple', 'banana'] },
  { type: 'vegetable', foods: ['potato'] }
]

সমাধান

const arr = [
  {food: 'apple', type: 'fruit'},
  {food: 'potato', type: 'vegetable'},
  {food: 'banana', type: 'fruit'},
];

const transformArray = (arr = []) => {
  const res = [];
  const map = {};
  let i, j, curr;
  for (i = 0, j = arr.length; i < j; i++) {
    curr = arr[i];
    if (!(curr.type in map)) {
      map[curr.type] = {type: curr.type, foods: []};
      res.push(map[curr.type]);
    }
    map[curr.type].foods.push(curr.food);
  }
  return res;
};

console.log(transformArray(arr));

আউটপুট

[
  { type: 'fruit', foods: [ 'apple', 'banana' ] },
  { type: 'vegetable', foods: [ 'potato' ] }
]

আধুনিক পদ্ধতি (ES6+)

const transformArrayModern = (arr = []) => 
  Object.values(arr.reduce((acc, {type, food}) => {
    acc[type] = acc[type] || {type, foods: []};
    acc[type].foods.push(food);
    return acc;
  }, {}));
  1. জাভাস্ক্রিপ্ট lastIndex প্রোপার্টি

  2. জাভাস্ক্রিপ্ট source প্রোপার্টি

  3. জাভাস্ক্রিপ্টে অবজেক্টের অ্যারে ID দিয়ে গ্রুপ করা

  4. জাভাস্ক্রিপ্টে ভ্যালু অনুযায়ী অবজেক্ট গ্রুপ করা