It would be incredibly helpful to have a versatile groupBy
function to streamline processes.
function groupBy(collection, fn) {
const groups = new Map();
for (const item of collection) {
const key = fn(item);
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(item);
}
return groups;
}
The groupBy
utility mentioned above can be applied to transform your data effectively.
const transformedData = Array.from(groupBy(data, item => item.category))
.map(([category, items]) => ({ id: items.map(item => item.id), category }));
This process rearranges your data as follows.
// group the items based on category
let transformedData = groupBy(data, item => item.category);
//=> {
// "Tech": [
// {id: 1, category: "Tech"},
// {id: 3, category: "Tech"},
// {id: 5, category: "Tech"}
// ],
// "Fashion": [
// {id: 2, category: "Fashion"}
// ],
// "Food": [
// {id: 4, category: "Food"}
// ]
// }
// convert the Map instance into an Array to utilize .map()
transformedData = Array.from(transformedData);
//=> [
// ["Tech", [
// {id: 1, category: "Tech"},
// {id: 3, category: "Tech"},
// {id: 5, category: "Tech"}
// ]],
// ["Fashion", [
// {id: 2, category: "Fashion"}
// ]],
// ["Food", [
// {id: 4, category: "Food"}
// ]]
// ]
// adjust the array into the desired format using .map()
transformedData = transformedData.map(([category, items]) => ({ id: items.map(item => item.id), category }));
//=> [
// { id: [1,3,5], category: "Tech" },
// { id: [2], category: "Fashion" },
// { id: [4], category: "Food" },
// ]
If you prefer the format 1~3~5
, change:
items.map(item => item.id)
// to
items.map(item => item.id).join("~")
const data = [
{id: 1, category: "Tech"},
{id: 2, category: "Fashion"},
{id: 3, category: "Tech"},
{id: 4, category: "Food"},
{id: 5, category: "Tech"}
];
const transformedData = Array.from(groupBy(data, item => item.category))
.map(([category, items]) => ({ id: items.map(item => item.id), category }));
console.log(transformedData);
function groupBy(collection, fn) {
const groups = new Map();
for (const item of collection) {
const key = fn(item);
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(item);
}
return groups;
}
References: