Node. The string array of strings does not work.

Hi, I am an absolute newbie 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 node.js code above reads the file as a string from the node.exe directory. Split a string using a newline ('\ n') to get an array. Sorts the array and prints the sorted array in the file. Thus, in general, the script reads the file, sorts the records, and saves the sorted record in another file. The problem is that the sorted order is incorrect. I tried to sort the contents of unsort.txt manually using MS Excel, with which I got the correct sort order. Can someone help me why arr.sort () is not working correctly. 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 these are just alphabets.

Examples from unsort.txt:

 appjs gbi node frame require process module WebSocket webkitAudioContext webkitRTCPeerConnection webkitPeerConnection00 webkitMediaStream MediaController HTMLSourceElement TimeRanges 
+4
source share
2 answers

If you do not pass the user search function, the sort function sorts lexically, the numbers are transferred to strings and, therefore, happens, for example, β€œ10” - to β€œ3”. Therefore, the rows are sorted.

You can pass a custom function to the sort function, which determines the order of elements, in the case of numbers it will be an example (be careful, since the numbers in your example will be strings if you do not display / parse them by 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; } 
+9
source

I would use

 arr.sort((obj1, obj2) => { return obj1.localeCompare(obj2); }); 

This will most likely solve your problem.

0
source

All Articles