JSFiddle - React, Tailwind, and code Playground

HTML

<pre id="res"></pre>

JavaScript

var list = [
      {id: 1, afterId: -1},
      {id: 5, afterId: 2},
      {id: 2, afterId: 4},
      {id: 4, afterId: 1},
      {id: 3, afterId: 5}
    ];

var newList = [];
var afterId = -1;
for (var i = 0; i < list.length; i++) {
    var item;
    for (var j = 0; j < list.length; j++) {
        if (list[j].afterId === afterId) {
            item = list[j];
            break;
        }
    }
    afterId = item.id;
    newList.push(item);
}


    // echo result
    document.getElementById('res').innerHTML = JSON.stringify( newList ).replace(/([\[\]]|\},|\})/g,'$&\n');