I'm trying to create a sort algo, that takes a list of items. Each item has the chance to define which item it comes after, if it doesn't then its natural position will be preserved based off the initial sorting.
Given the data set looks like.....
[
{
"id": 1871,
"after": null,
},
{
"id": 1872,
"after": null,
},
{
"id": 1873,
"after": 1872,
},
{
"id": 1874,
"after": 1872,
},
{
"id": 1875,
"after": 1873,
},
{
"id": 1876,
"after": 1875,
},
{
"id": 1877,
"after": 1876,
},
{
"id": 1878,
"after": 1877,
},
{
"id": 1879,
"after": null,
},
{
"id": 1880,
"after": 1874,
},
]
The idea is that it recursively sorts the array until it's resolved as possible, placing the items in the correct order based numerically from the "id" property, if the item contains an "after" value it should be placed immediately after the element, So the correct order would look like.....
[
{
"id": 1871,
"after": null,
},
{
"id": 1872,
"after": null,
},
{
"id": 1873,
"after": 1872,
},
{
"id": 1875,
"after": 1873,
},
{
"id": 1876,
"after": 1875,
},
{
"id": 1877,
"after": 1876,
},
{
"id": 1878,
"after": 1877,
},
{
"id": 1874,
"after": 1872,
},
{
"id": 1880,
"after": 1874,
},
{
"id": 1879,
"after": null,
},
]
Can somebody provide a sort function that can solve this?
Thanks