সমস্যা বিবরণ
ফ্রুট এবং ভেজিটেবল ডেটা সম্বন্ধীয় একটি অবজেক্ট অ্যারে দেওয়া আছে। 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;
}, {}));