I have an unsorted objects array with strings like this:
const unsortedArr = [
{
id: "test13",
startAfter: "test15"
},
{
id: "test20",
startAfter: "test5"
},
{
id: "test5",
startAfter: "test1"
},
{
id: "test15",
startAfter: "test20"
},
]
You get the idea.
I also have a start ID: const startId = "test1";
With my start ID as the first value, I want to sort the array according to the "startAfter" property. Create a chronological chain, so to speak.
The result should look like this:
const sortedArr = [
{
id: "test5",
startAfter: "test1"
},
{
id: "test20",
startAfter: "test5"
},
{
id: "test15",
startAfter: "test20"
},
{
id: "test13",
startAfter: "test15"
},
]
What is the easiest way to sort this array in JS?
2
Answers
What you have is a linked list, but it lacks the possibility to locate an object by id in constant time. So I’d suggest creating a Map for that first, and then you can create the sorted array by looking up the next id from the current node:
You can achieve this by creating a map of the array and then iterating over the
map
starting from thestartId