Created
March 28, 2012 11:54
-
-
Save lepture/2225611 to your computer and use it in GitHub Desktop.
find and sort in js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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