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
To sort an array of strings in Java, we can use Arrays. sort() function.
This is because sort() needs a callback comparator, and when sort() is used without one, String() acts as the default callback. This is our callback function that will help sort the numbers in the correct and ascending order.
sort() is an array function from Node. js that is used to sort a given array. Parameter: This function does not takes any parameter. Return type: The function returns the sorted array.
Using sort() method: In this method, we use predefined sort() method of JavaScript to sort the array of string. This method is used only when the string is alphabetic. It will produce wrong results if we store numbers in an array and apply this method.
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;
if (a > b) return -1;
return 0;
}
I would use
arr.sort((obj1, obj2) => {
return obj1.localeCompare(obj2);
});
That will most likely solve your issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With