6

Sorting the table Ignoring special characters and integers?

 3 years ago
source link: https://www.codesd.com/item/sorting-the-table-ignoring-special-characters-and-integers.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Sorting the table Ignoring special characters and integers?

advertisements

I have been trying to sort and array with strings composed of letters, integers and characters. Here is what I have done:

var vList =["IEC - 62877-1 ", "IEC - 60622 ", "CAN/CSA - F382-M89 (2014) ", "Telcordia - GR-3150-CORE ", "UL - 1973"];

vList.sort(function(a,b) {
return a.split(' - ')[0] - b.split(' - ')[0];
});

print(vList)

The idea is to sort the array in alphabetical order by using the first letter only element of the string: "IEC", "CAN", "Telecordia", "UL".

the array should look like this:

vList = ["CAN/CSA - F382-M89 (2014)", "IEC - 62877-1 ", "IEC - 60622 ","Telcordia - GR-3150-CORE ", "UL - 1973"];


Your solution is very special for your case. However, you have to describe your strings either with a regex or, like you, by splitting it or doing some other stuff. Repair your method to:

vList.sort(function(a,b) {
  return a.split(' - ')[0].localCompare(b.split(' - ')[0]);
});

That uses a local (to the browser language) comparison of strings and returns the correct value.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK