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

জাভাস্ক্রিপ্টে অ্যারে গ্রুপিং এবং আইটেম কাউন্ট করে গ্রুপ ভিত্তিক নতুন অ্যারে তৈরি করা

ধরুন, আমাদের নিচের মত একটি অবজেক্ট অ্যারে আছে:

const arr = [    { region: "Africa", fruit: "Orange", user: "Gary" },    { region: "Africa", fruit: "Apple", user: "Steve" },    { region: "Europe", fruit: "Orange", user: "John" },    { region: "Europe", fruit: "Apple", user: "bob" },    { region: "Asia", fruit: "Orange", user: "Ian" },    { region: "Asia", fruit: "Apple", user: "Angelo" },    { region: "Africa", fruit: "Orange", user: "Gary" } ];

আমাদের একটি ফাংশন লিখতে হবে যা এমন একটি অ্যারে নিবে। ফাংশনটি অবজেক্টের "area" প্রোপার্টি অনুযায়ী ডেটা গ্রুপ করে একটি নতুন অবজেক্ট অ্যারে তৈরি করবে। ফাংশনটি প্রতিটি এরিয়ার জন্য ইউনিক ইউজারের কাউন্টও রাখবে।

উপরের অ্যারেতে আউটপুট হবে এমন:

const output = [    {       "region": "Africa",       "count": 2    },    {       "region": "Europe",       "count": 2    },    {       "region": "Asia",       "count": 2    } ];

উদাহরণ

এটির কোড হবে:

const arr = [    { region: "Africa", fruit: "Orange", user: "Gary" },    { region: "Africa", fruit: "Apple", user: "Steve" },    { region: "Europe", fruit: "Orange", user: "John" },    { region: "Europe", fruit: "Apple", user: "bob" },    { region: "Asia", fruit: "Orange", user: "Ian" },    { region: "Asia", fruit: "Apple", user: "Angelo" },    { region: "Africa", fruit: "Orange", user: "Gary" } ]; const groupByArea = (arr = []) => {    const res = [];    arr.forEach(el => {       let key = [el.region, el.user].join('|');       if (!this[el.region]) {          this[el.region] = { region: el.region, count: 0 };          res.push(this[el.region]);       };       if (!this[key]) {          this[key] = true;          this[el.region].count++;       };    }, Object.create(null));    return res; } console.log(groupByArea(arr));

আউটপুট

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

[    { region: 'Africa', count: 2 },    { region: 'Europe', count: 2 },    { region: 'Asia', count: 2 } ]
  1. জাভাস্ক্রিপ্ট অ্যারে মেথড: অ্যারেতে আইটেম যোগ ও সরানো

  2. জাভাস্ক্রিপ্টে new কীওয়ার্ড দিয়ে অ্যারে তৈরির পদ্ধতি

  3. জাভাস্ক্রিপ্ট অবজেক্টকে নতুন অ্যারেতে ফরম্যাট করা

  4. জাভাস্ক্রিপ্টে ক্যারেক্টার ম্যাট্রিক্স ও নম্বর অ্যারে দিয়ে স্ট্রিং তৈরি করা