JSFiddle - React, Tailwind, and code Playground

by Mourad Kejji

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){
     if (a.afterId == -1 || b.afterId == a.id) {
     return -1;
     }
     if (b.afterId == -1 || a.afterId == b.id) {
     return 1;
     }
      return 0;

    });


    // echo result
    document.getElementById('res').innerHTML = JSON.stringify( list, null, 2 );