Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.JS string array sort is not working

Node.JS string array sort is not working

Problem

Hi I am absolute beginner of node.js Today I tried the following code

var fs, arr;
var dir, str;
var cont, item;

fs=require('fs');
cont=fs.readFileSync('unsort.txt').toString();
arr=cont.split('\n');
arr.sort();

for(str=arr.shift();str&&(item=arr.shift());)
    str+='\n'+item;
fs.writeFileSync('sort_by_script.txt', str);

the above node.js code reads a file as string, from the directory of the node.exe. Splits the string by newline ('\n') to get a array. Sorts the array and prints the sorted array to the file. So as a whole the script reads a file sort the entries and saves the sorted entry in another file. The problem is the sorted order is not correct. I tried sorting the content of unsort.txt manually using MS Excel by which I got the correct order of sort. Can any one help me why the arr.sort() is not working correct. You can download unsort.txt, sort_by_script.txt, sort_by_ms_excel.txt and node.exe in the package [Sort.rar][1]

Note : unsort.txt has no numbers. All are only alphabets.

Examples from unsort.txt:

appjs
gbi
node
frame
require
process
module
WebSocket
webkitAudioContext
webkitRTCPeerConnection
webkitPeerConnection00
webkitMediaStream
MediaController
HTMLSourceElement
TimeRanges
Problem courtesy of: Dinesh

Solution

If you do not pass a custom search function the sort function sorts lexically, numbers get cast to strings and so it happens that e.g. "10" is before "3". So the strings get sorted.

You can pass a custom function to the sort function which decides the order of the items, in case of numbers this would be an example (Be careful as numbers in your example would be strings if you dont cast / parse them to numbers) :

var numsort = function (a, b) {
    return a - b;
}

var numbers = new Array(20, 2, 11, 4, 1);

var result = numbers.sort(numsort);

Another example for strings:

var sortstring = function (a, b)    {
    a = a.toLowerCase();
    b = b.toLowerCase();
    if (a  b) return -1;
    return 0;
}
Solution courtesy of: pfried

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.JS string array sort is not working

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×