Creating a general groupBy
helper would simplify things quite a bit.
function groupBy(iterable, fn) {
const groups = new Map();
for (const item of iterable) {
const key = fn(item);
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(item);
}
return groups;
}
With the above helper you can use the following transform your data.
const result = Array.from(groupBy(data, item => item.label))
.map(([label, items]) => ({ id: items.map(item => item.id), label }));
This does the following to your data.
// group the items based on label
let result = groupBy(data, item => item.label);
//=> { // <- Map instance displayed as plain JS object
// "Hello": [
// {id: 1, label: "Hello"},
// {id: 3, label: "Hello"},
// {id: 5, label: "Hello"}
// ],
// "World": [
// {id: 2, label: "World"}
// ],
// "Sunshine": [
// {id: 4, label: "Sunshine"}
// ]
// }
// change the Map instance into an Array so we can use .map()
result = Array.from(result);
//=> [
// ["Hello", [
// {id: 1, label: "Hello"},
// {id: 3, label: "Hello"},
// {id: 5, label: "Hello"}
// ]],
// ["World", [
// {id: 2, label: "World"}
// ]],
// ["Sunshine", [
// {id: 4, label: "Sunshine"}
// ]]
// ]
// convert the array into the desired format using .map()
result = result.map(([label, items]) => ({ id: items.map(item => item.id), label }));
//=> [
// { id: [1,3,5], label: "Hello" },
// { id: [2], label: "World" },
// { id: [4], label: "Sunshine" },
// ]
I'm not quite sure why you are looking for the 1~3~5
format, using an array seems more logical. If you however insist on using 1~3~5
change:
items.map(item => item.id)
// into
items.map(item => item.id).join("~")
const data = [
{id: 1, label: "Hello"},
{id: 2, label: "World"},
{id: 3, label: "Hello"},
{id: 4, label: "Sunshine"},
{id: 5, label: "Hello"}
];
const result = Array.from(groupBy(data, item => item.label))
.map(([label, items]) => ({ id: items.map(item => item.id), label }));
console.log(result);
function groupBy(iterable, fn) {
const groups = new Map();
for (const item of iterable) {
const key = fn(item);
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(item);
}
return groups;
}
References: