Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>My other answer explains why your sort does not work stable. This one will solve your actual problem :-)</p> <p>You can't use a <code>sort</code> for this type of problem, where you want to construct a list of nodes from a (unordered) set of edges. Sorting an array is only applicable if you can <em>compare</em> two of the elements without additional data. Say you have only the two connections <code>Tokio - Moscow</code> and <code>Rome - Oslo</code>, you don't know which of them comes first (without contacting your plan, but you don't have that yet). In contrast, when comparing numbers you can easily and always tell that 5 is bigger than 3 (by computing the difference).</p> <p>Instead, we need to do something like <a href="https://stackoverflow.com/a/12048098/1048572">this</a> or <a href="https://stackoverflow.com/a/14252219/1048572">this</a> - build a structure where we can easily access a station by name and insert connections directly when we encounter them during looping them, so that in the end we have a list of connections by station:</p> <pre><code>var map = {}; for (var i=0; i&lt;arr.length; i++) { var con = arr[i]; map[con.from] = con; } </code></pre> <p>So that we can now construct your route as some kind of linked list:</p> <pre><code>for (var from in map) { var connTo = map[from].to; if (connTo in map) map[from].next = map[connTo]; } </code></pre> <p>And find the start station by deleting all destinations from the map:</p> <pre><code>for (var from in map) for (var next = map[from]; next; next = next.next) delete map[next.to]; for (from in map) // there's only one key left var start = from; // "Helsinki" </code></pre> <p>Let's construct the route as an array of station names:</p> <pre><code>var route = [start], conn = map[start]; while (conn) { route.push(conn.to) conn = conn.next; // maybe delete conn.next as we don't need it any more } // route: // ["Helsinki", "Tokio", "Moscow", "Rome", "Oslo", "Paris", "New-York"] </code></pre> <p>or the result which you want, the list of connections:</p> <pre><code>var arr = []; for (var conn = map[start]; conn; conn = conn.next) arr.push(conn); </code></pre> <hr> <p>Having that plan, we even could now construct a compare-function to sort the original array:</p> <pre><code>arr.sort(function(a, b) { // compare the positions of the departure stations in the route return route.indexOf(a.from) - route.indexOf(b.from); }); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload