Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom case insensitive sort function that retains original casing?

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.

like image 908
mcabrams Avatar asked Jan 13 '13 22:01

mcabrams


Video Answer


1 Answers

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"
like image 150
Tomasz Nurkiewicz Avatar answered Sep 28 '22 18:09

Tomasz Nurkiewicz