Hello everyone I still can’t sort the array correctly. We need to sort the following array:
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 – array to sort
- newArr – is an array that should turn out to be
So that the topmost elements have parentId: 0o000
, and their lowest children, who have the same parentId
id
, and so on, there can be as many elements as you like.
If the parentId
is the same for several elements, then child
comes first, the most recent block
and its children below, if there are any.
I tried to add to a new array by the parentId
property, but in the end the order of the elements was lost