I've completed an exercise in Modern JavaScript to create a page that takes a string of words and sorts them in a case-insensitive manner. Here's the codepen: http://codepen.io/Mcabrams/full/FvuJg:
// relevant code:
var sorted = words.map(function(value){
return value.toLowerCase();
}).sort();
I want to know how I would go around making a similar function to sortWords()
, but while sorting in a case-insensitive manner, when I return the sorted words, I would like to maintain the original casing.
Example of desired functionality:
sortWords(["D","b","A","c"]) ======> ["A", "b", "c", "D"]
Currently the original casing is lost in my function.
Use custom comparator in built-in Array.sort()
method:
function insensitive(s1, s2) {
var s1lower = s1.toLowerCase();
var s2lower = s2.toLowerCase();
return s1lower > s2lower? 1 : (s1lower < s2lower? -1 : 0);
}
["D","b","A","c"].sort(insensitive); //"A", "b", "c", "D"
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