I have structure like this:
[
{id: 1, afterId: -1},
{id: 5, afterId: 2},
{id: 2, afterId: 4},
{id: 4, afterId: 1},
{id: 3, afterId: 5}
]
Edited
Requirements:
- Each object's afterId must be equal to previous object id key;
- Object with afterId = -1 must be first;
- Should work even if there is duplicated or missing afterId's;
Expected result:
[
{id: 1, afterId: -1},
{id: 4, afterId: 1},
{id: 2, afterId: 4},
{id: 5, afterId: 2},
{id: 3, afterId: 5}
]
Example: http://jsfiddle.net/z3sfdo1z/