Hey everyone, I'm still having trouble sorting out this array properly. The array we need to sort is as follows:
const arr = [
{id: 3123124, parentId: 0o0000, title: 'title', type: 'block'},
{id: 3542132, parentId: 3123124, title: 'title', type: 'child'},
{id: 12345, parentId: 88888, title: 'title', type: 'block'},
{id: 24124, parentId: 12345, title: 'title', type: 'child'},
{id: 99999, parentId: 45324, title: 'title', type: 'child'},
{id: 986648, parentId: 3123124, title: 'title', type: 'block'},
{id: 77777, parentId: 88888, title: 'title', type: 'child'},
{id: 54232, parentId: 3123124, title: 'title', type: 'child'},
{id: 54308, parentId: 15075, title: 'title', type: 'child'},
{id: 66666, parentId: 88888, title: 'title', type: 'block'},
{id: 56445, parentId: 12345, title: 'title', type: 'child'},
{id: 88888, parentId: 45324, title: 'title', type: 'block'},
{id: 15075, parentId: 12345, title: 'title', type: 'block'},
{id: 84356, parentId: 66666, title: 'title', type: 'child'},
{id: 45324, parentId: 0o0000, title: 'title', type: 'block'},
]
const newArr = [
{id: 3123124, parentId: 0o0000, title: 'title', type: 'block'},
{id: 3542132, parentId: 3123124, title: 'title', type: 'child'},
{id: 54232, parentId: 3123124, title: 'title', type: 'child'},
{id: 986648, parentId: 3123124, title: 'title', type: 'block'},
{id: 45324, parentId: 0o0000, title: 'title', type: 'block'},
{id: 99999, parentId: 45324, title: 'title', type: 'child'},
{id: 88888, parentId: 45324, title: 'title', type: 'block'},
{id: 77777, parentId: 88888, title: 'title', type: 'child'},
{id: 12345, parentId: 88888, title: 'title', type: 'block'},
{id: 56445, parentId: 12345, title: 'title', type: 'child'},
{id: 24124, parentId: 12345, title: 'title', type: 'child'},
{id: 15075, parentId: 12345, title: 'title', type: 'block'},
{id: 54308, parentId: 15075, title: 'title', type: 'child'},
{id: 66666, parentId: 88888, title: 'title', type: 'block'},
{id: 84356, parentId: 66666, title: 'title', type: 'child'},
]
- arr - the array that needs to be sorted
- newArr - the desired output array after sorting
We want the elements with parentId: 0o000
at the top, followed by their children with matching parentId
, and so on. If multiple elements have the same parentId
, children should come first, then the most recent block and its children below it.
I attempted to add elements to a new array based on the parentId
property, but ended up losing the original order of the elements.