A new feature I would like to suggest is a universal groupBy()
function that facilitates grouping a collection based on a specific key.
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;
}
Using this function allows us to categorize data by:
const groups = groupBy(input_array, item => JSON.stringify([item.name, item.day]));
The choice to use JSON.stringify()
is deliberate as two arrays are considered equal only if they reference the same array. Thus, creating a new array instance like [item.name, item.day]
will never match an existing key. Serializing the array using JSON allows comparison between strings instead, making the process feasible.
// normal array comparison
["alagu", "monday"] === ["alagu", "monday"] //=> false
// serialized (using JSON) array comparison
'["alagu","monday"]' === '["alagu","monday"]' //=> true
Once the data is grouped, the structure of groups
appears as follows:
// displaying Map instance contents in object notation
Map{
'["alagu","monday"]': [
{ name: "alagu", day: "monday", time: "morning", task: "studying" },
{ name: "alagu", day: "monday", time: "evening", task: "playing" },
{ name: "alagu", day: "monday", time: "night" , task: "sleeping" },
],
'["alagu","sunday"]': [
{ name: "alagu", day: "sunday", time: "morning", task: "playing" },
{ name: "alagu", day: "sunday", time: "evening", task: "playing" },
{ name: "alagu", day: "sunday", time: "night" , task: "sleeping" },
],
}
To convert this into an array, we can utilize Array.from(groups)
and provide custom transformations through map()
.
const result_array = Array.from(groups).map(([json, items]) => {
const [name, day] = JSON.parse(json);
const schedule = items.map(({ time, task }) => ({ time, task }));
return { name, day, schedule };
});
In the above implementation, the serialized key is decoded back into its original JavaScript form using JSON.parse()
, enabling retrieval of the name
and day
values of each group.
The next step involves transforming items
, an array containing all properties, into objects with only time
and task
attributes.
.map(({ time, task }) => ({ time, task }))
achieves this goal efficiently, combining object destructuring with property shorthand syntax.