Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think the cleanest way is to push the results from each dataset into an externally scoped variable, then sort and render from that. Example is below.</p> <pre><code>var combined = [], completed = 0; $(document).ready(function () { $("#search").keyup(function () { combined = []; completed = 0; $.getJSON("http://suggestqueries.google.com/complete/search?q=" + $("#search").val() + "&amp;client=chrome&amp;callback=?", function (data) { for (var key in data[1]) { if (data[4]["google:suggesttype"][key] == "NAVIGATION") { combined.push({ href : data[1][key], text : data[2][key], score : parseInt(data[4]["google:suggestrelevance"][key],10) }); } else { combined.push({ text : data[1][key], score : parseInt(data[4]["google:suggestrelevance"][key],10) }); } } if ( ++completed == 2 ) complete(); }); $.getJSON("https://www.googleapis.com/freebase/v1/search?query=" + $("#search").val() + "&amp;limit=3&amp;encode=html&amp;callback=?", function (data) { for (var key in data.result) { combined.push({ text : data.result[key].name, score : parseInt(data.result[key].score,10) * 14 }); } if ( ++completed == 2 ) complete(); }); }); }); function complete(){ console.log(combined); combined.sort(function(a,b){ return b.score - a.score; }); var buffer = []; combined.forEach(function(result){ buffer.push("&lt;li&gt;"+result.text+" &lt;i&gt;("+result.score+")&lt;/i&gt;&lt;/li&gt;") }) $("#suggest").html(buffer.join("")); } </code></pre> <p><strong>Edit</strong></p> <p>This solution doesn't take into account the fact that the user may be typing at a faster pace than the APIs, that API calls may not come back in order, and doesn't do anything to try to limit the number of calls made to each API. To make this behave more consistently (and more efficiently):</p> <ul> <li>Change the keypress handler such that each key press cancels any previous timeouts then sets a new timeout at a reasonable delay (300ms seems a reasonable place to start) which then triggers the API calls</li> <li>Wrap each API call in an immediately executed function so that you can reference the value of a global counter at the time each API call was made. Increment the counter with each keypress, and don't process the response from API calls where the counter didn't match</li> </ul>
 

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