I'm working on an array of object to group them according to the key(number), but it always ends up sorting the array. So is there any solution using Map() to perform group by or any TypeScript solution for it.
const reGroup = (list, key) => {
const newGroup = {};
list.forEach(item => {
const newItem = Object.assign({}, item);
newGroup[item[key]] = newGroup[item[key]] || [];
newGroup[item[key]].push(newItem);
});
return newGroup;
};
const pets = [
{type:"Dog", age: "5", name:"Spot", },
{type:"Cat", age: "3", name:"Tiger",},
{type:"Dog", age: "2", name:"Rover", },
{type:"Cat", age: "3", name:"Leo", }
];
const grouped = reGroup(pets, "age");
console.log(grouped);
Output:
{
"2": [ { "type": "Dog", "age": "2", "name": "Rover" } ],
"3": [ { "type": "Cat", "age": "3", "name": "Tiger" },
{ "type": "Cat", "age": "3", "name": "Leo" } ],
"5": [ { "type": "Dog", "age": "5", "name": "Spot" } ]
}
Expected:
{
"5": [ { "type": "Dog", "age": "5", "name": "Spot" } ],
"3": [ { "type": "Cat", "age": "3", "name": "Tiger" },
{ "type": "Cat", "age": "3", "name": "Leo" } ],
"2": [ { "type": "Dog", "age": "2", "name": "Rover" } ],
}
Use an array instead of an object. Order of keys in objects cannot be guaranteed.
Try:
const reGroup = (list, key) => {
const groups = [];
list.forEach(item => {
let groupIndex = groups.findIndex((gi) => gi.key === item[key]);
if (groupIndex === -1) {
// when the group containing object does not exist in the array,
// create it
groups.push({key: item[key], items: []});
groupIndex = groups.length - 1;
}
const newItem = Object.assign({}, item);
groups[groupIndex].items.push(newItem);
});
return groups;
};
const pets = [
{type:"Dog", age: "5", name:"Spot", },
{type:"Cat", age: "3", name:"Tiger",},
{type:"Dog", age: "2", name:"Rover", },
{type:"Cat", age: "3", name:"Leo", }
];
const grouped = reGroup(pets, "age");
console.log(JSON.stringify(grouped, null, 2));
which logs:
[
{
"key": "5",
"items": [
{
"type": "Dog",
"age": "5",
"name": "Spot"
}
]
},
{
"key": "3",
"items": [
{
"type": "Cat",
"age": "3",
"name": "Tiger"
},
{
"type": "Cat",
"age": "3",
"name": "Leo"
}
]
},
{
"key": "2",
"items": [
{
"type": "Dog",
"age": "2",
"name": "Rover"
}
]
}
]