Skip to content Skip to sidebar Skip to footer

How Do I Sort Alphabetically And Lower Case First

How do I get the result of the below sorting be Food to Eat then 'FOOD 123'. Apparently, the 2nd lower 'o' should bring Food to Eat to the first item after sorting. I'm surprised t

Solution 1:

It seems that String.prototype.localeCompare accepts options, that can be found here. sensitivity: 'case' should achieve what you are looking for.

Solution 2:

You could take a custom sorting approach and separate the characters into groups and then sort the strings of the temporary array.

var array = ["FOOD 123", "Food to Eat", 'banana', 'Banana', 'BANANA'],
    result = array
        .map((string, index) => ({ index, value: Array.from(string, c => c === c.toLowerCase() ? ' ' + c : c + ' ').join('') }))
        .sort((a, b) => a.value.localeCompare(b.value))
        .map(({ index }) => array[index]);

console.log(result);

Post a Comment for "How Do I Sort Alphabetically And Lower Case First"