Skip to content

Instantly share code, notes, and snippets.

@lepture
Created March 28, 2012 11:54
Show Gist options
  • Save lepture/2225611 to your computer and use it in GitHub Desktop.
Save lepture/2225611 to your computer and use it in GitHub Desktop.
find and sort in js
var find = function(data, word){
if(!word.length) return [];
var results = [];
var fuzzyResults = [];
for (i=0; i<data.length; i++) {
var _fuzzy = true;
var item = data[i];
if(item.key.toLowerCase().indexOf(word) != -1){
item.order = item.key.toLowerCase().indexOf(word);
results.push(item);
_fuzzy = false;
}
if(_fuzzy && item.text.toLowerCase().indexOf(word) != -1){
item.order = item.text.toLowerCase().indexOf(word) + 2;
fuzzyResults.push(item);
_fuzzy = false;
}
if(_fuzzy && item.url.indexOf(word) != -1) {
item.order = item.url.toLowerCase().indexOf(word) + 9;
fuzzyResults.push(item);
}
}
results.push.apply(results, fuzzyResults);
var _sort = function(a, b){ return a.order - b.order}
results.sort(_sort);
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment