Array Sort On The Basis Of Search Text Matching Using Pure Javascript
I am working on some suitable way of sorting an array on the basis of search string. For example here is an array var myarray = ['2386', '1234', '3867']; and here is the string wh
Solution 1:
I have used levinstien for the string comparison, you can check the fiddle demo.
levenstien source = https://github.com/gf3/Levenshtein,
my code is
functioncompare(a, b) {
var leva = newLevenshtein(a,searchkey).distance;
var levb = newLevenshtein(b,searchkey).distance;
return leva-levb;
}
var myarray = ["2386", "1234", "3867"];
var searchkey = "123";
myarray.sort(compare);
Solution 2:
var myarray = ["2386", "1234", "3867"], searchkey = '123';
functionmySort(arrKeys,searchkey){
var matchedKeys = [], notMatchedKeys = [];
for(var i = 0; i < arrKeys.length; i++) {
if (arrKeys[i].match(searchkey) ) {//dummy logic
matchedKeys.push(arrKeys[i]);//push on the basis of order
}else{
notMatchedKeys.push(arrKeys[i]);
}
}
return matchedKeys.concat(notMatchedKeys);
}
console.log( mySort(myarray,searchkey));
Post a Comment for "Array Sort On The Basis Of Search Text Matching Using Pure Javascript"