Recently, I was looking fro a Javascript function or a tutorial on how to sort an array based on the position of a character in an input string. For instance, if I have 20 names in an array and I type “s” in the text box the result should give me all the names that have the character “s” but they should also sorted according to the position on which the character is found.
We will take 2 names “somen” and “ashutosh” In popular sorting functions the name “ashutosh” will occur before the name “somen” in the above example as the sorting is done for the whole word beginning with the first character the name “ashutosh” occurs first. But I wanted the name “somen” to occur first since the character “s” is positioned at the beginning. |
Following is the function I created to achieve this- |
abinash,supriti,mohanish,amitabh,premananda,durdarshan, mindfire,grahacharya,acharya,mukulika,danish,jeetendra,debasis, sujata,priyadarshan,chittaranjan
var data_v = document.getElementById('TextArea1').value; var character_search = document.getElementById('sortval').value; var newstring = abinashsort(data_v,character_search); if(newstring == 0) { document.getElementById('disp').style.display='none'; } else if(newstring != 0) { newstring = newstring.split(","); var newstr =''; for(var i=0; i