ধরুন, আমাদের নিচের মত একটি অবজেক্ট অ্যারে আছে:
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 } ]