The default behavior of the sort() method is to sort uppercase letters before lowercase letters.
let arr = ['Pastry', 'Doughnut', 'cupcake', 'lollipop', 'Kitkat']; arr.sort(); console.log(arr); //["Doughnut", "Kitkat", "Pastry", "cupcake", "lollipop"]
However, if you want to sort array elements ignoring the case, then pass the comparison function to the sort()
method.
Inside the comparison function, convert both arguments to lowercase by calling the toLowerCase() method. After that, return 1 when the first argument is greater than the second argument. If the second argument is greater than the first one, return -1.
let arr = ['Pastry', 'Doughnut', 'cupcake', 'lollipop', 'Kitkat']; arr.sort((a, b)=>{ if(a.toLowerCase() > b.toLowerCase()){ return 1; }else{ return -1; } }); console.log(arr); //["cupcake", "Doughnut", "Kitkat", "lollipop", "Pastry"]
Here is the explanation of the code:
1. By default, the sort() method modifies the original array, so if you don't want to update the original array, copy it using the spread operator.
let arr = ['Pastry', 'Doughnut', 'cupcake', 'lollipop', 'Kitkat']; let copiedArr = [...arr];
2. Array elements are sorted based on the value returned by the comparison function. If the returned value is greater than 0, the second argument is sorted before the first argument. On the other hand, if the returned value is less than 0, then the first argument comes before the second one. At last, if both arguments are equal, then return 0.
arr.sort((a, b)=>{ if(a.toLowerCase() > b.toLowerCase()){ return 1; }else{ return -1; } });