Thanks alot @Manan Joshi but i need to understand what is happening! , the javascript learning is long journey! :), so please let me tell you what i basically understand from the updated code, in the first four lines i understand this method is organized and easy to update also the last line,but what i really need to understand is the sorting itself, its something looks like GREP, maybe it mean to sort by page number only but really i cant get exactly the full meaning, can you please explain more about this method? and thanks again.
Ok, let me try adding some description to the code I shared.
The changes in the for loop are to make the entries in a defined format which would help us design our sorting approach in the later stage. Each entry in the array is created in the following format
<Content of the found element><tab character><the page number where the content is found>
Now we get to sort the array with each element in the format defined above. In the sort method we can pass as an argument a function that determines the comparison(equality, greater than, less than) of two values of the array.
For details on the sort method, I list the function description below
Array.sort (userFunction: Function )
Core JavaScript Classes
Sorts the elements of the array in place, using the given function to compare to elements.
If no function is provided, the elements are sorted alphabetically. Returns no return value.
userFunction: Data Type: Function
A user-supplied function of the form userFunction(a, b) which returns less than 0 if a is greater than b, 0 if a and b are equal, and greater than 0 if b is greater than a.
Example:
array.sort(userFunction)
Now all we are left with is to define this function. In this function I use grep to extract the page numbers from each array entry and then use that to determine the order between two array values. Here I did not provision for the cases where the page numbers are same for both array values, in such a case my code will consider both the values as equal. However you can augment the sort function to consider text sorting in cases where the page numbers are equal.
Finally after sorting we join the array elements with a new line between each entry.
I hope you get the drift of what I did and would now be able to use it or change the sort function as per your needs.
-Manan