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}
    ];


    list.sort(function(a,b){
     
      return a.afterId === b.id ? 1 : 0;

    });


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