I would like to convert an array of objects that looks like:
const children = [
{ name: c1, parent: p1, draw_order: 1 },
{ name: c2, parent: p2, draw_order: 2 },
{ name: c3, parent: p2, draw_order: 4 },
{ name: c4, parent: p1, draw_order: 3 },
{ name: c5, parent: p3, draw_order: 1 },
];
1. I want to make a new array that contains parent object like:
const parents = [
{ name:p1, draw_order: 1, children: [...] },
{ name:p2, draw_order: 2, children: [...] },
{ name:p3, draw_order: 1, children: [...] },
]
The draw_order of parent Object should be equal to the lowest value of the children's draw_order values.
Something like:
const parents = [];
children.forEach(c => {
const parent = parents.find(p => p.name === c.name);
parent ? parents.children.push(c) : parents.push({name: c.parent, children:[c})
})
parents.forEach(p => {
const drawOrder = Math.min(...p.children.map(c => c.drawOrder));
p.draw_order = drawOrder;
})
2. The parents now have repeated draw_order - 1, 2, 1;
I Would like to Update it to:
1 => 1, 2 => 3, 1 => 2
if the values are: [1, 3, 4, 4, 1, 3, 2]
1 => 1
3 => 4
4 => 6
4 => 7
1 => 2
3 => 5
2 => 3
The final result should be:
const parents = [
{ name:p1, draw_order: 1, children: [...] },
{ name:p2, draw_order: 3, children: [...] },
{ name:p3, draw_order: 2, children: [...] },
]
Just for checking if we have:
const children = [
{ name: c1, parent: p1, draw_order: 1 },
{ name: c2, parent: p8, draw_order: 2 },
{ name: c3, parent: p2, draw_order: 4 },
{ name: c4, parent: p1, draw_order: 3 },
{ name: c5, parent: p4, draw_order: 3 },
{ name: c6, parent: p4, draw_order: 9 },
{ name: c7, parent: p3, draw_order: 1 },
];
The outPuts should be
const parents = [
{ name:p1, draw_order: 1, children: [...] },
{ name:p2, draw_order: 5, children: [...] },
{ name:p3, draw_order: 2, children: [...] },
{ name:p4, draw_order: 4, children: [...] },
{ name:p8, draw_order: 3, children: [...] },
]
Thanks
question from:
https://stackoverflow.com/questions/65829291/javascript-special-sorting-array-of-objects-by-value-and-parent