Here is the code snippet I am working with:
const info = {
detail : {
id: "1",
name: "aa",
category: [
{
id:"11",
order:0,
},
{
id:"33",
order:5,
},
{
id:"3",
order:1,
},
]
},
detail2 : {
id: "2",
name: "aaa",
category: [
{
id:"111",
order:3,
},
{
id:"33",
order:1,
},
{
id:"3",
order:2,
},
]
}
}
I am trying to rearrange the category
objects based on their order
. I attempted to use the following piece of code:
info.category.sort((x, y) => {
return x.order - y.order || x.order.localeCompare(y.order);
});
Unfortunately, this implementation ends up replacing the elements and only retaining the last one. There seems to be something missing for it to work as intended.
The desired output should look like this:
const finalInfo = {
detail : {
id: "1",
name: "aa",
category: [
{
id:"11",
order:0,
},
{
id:"3",
order:1,
},
{
id:"33",
order:5,
},
]
},
detail2 : {
id: "2",
name: "aaa",
category: [
{
id:"33",
order:1,
},
{
id:"3",
order:2,
},
{
id:"111",
order:3,
},
]
}
}
How can I achieve that?