I have a search-function, that searches for specific data within a huge Object.
Depending on how good a found entry matches, the finding gets "matchPoints" (or "Priority")
var findings = {};
for(var element in hugeObject){
var points = getMatchPoints( inputToSearchFor, hugeObject[element] );
if( points !== 0 ){ //It matched. At least a bit.
findings[ points ] = element;
}
}
Now I have all Elements, that somehow matched, within findings
.
The function which implements this has to return an Array of all these elements. The most relevant result on the first place.
I currently use this for sorting:
var priorities = Object.keys(findings); //Get the matchpoints of all findings
priorities.reverse(); //Sort with reverse order (highest priority / most matchpoints first)
var result = [];
for(var i=0; i<priorities.length; i++){
result.push( findings[i] );
}
return result;
I have several issues with this code:
- It is inefficient and probably very slow
- The
.reverse()
function sorts the priorities alphabetically, not numerically - If 2 findings have the same amount of matchpoints, the
findings
-entry gets overwritten. So the result isn't even valid.
How can I solve this problem in an efficient and elegant way?
Edit: I should mention, that although the object where I search is very big, I only get few valid results which matchPoints > 0. In fact, most of the time I'll get only 2-3 matches at all.