diff --git a/javascript/sort-alphabetically.md b/javascript/sort-alphabetically.md new file mode 100644 index 0000000..2db9bdf --- /dev/null +++ b/javascript/sort-alphabetically.md @@ -0,0 +1,40 @@ +# Sort Alphabetically + +```javascript +const people = [ + { firstName: "Aaron", lastName: "Smith" }, + { firstName: "Émile", lastName: "Zola" }, + { firstName: "Charlotte", lastName: "Brown" }, + { firstName: "Beyoncé", lastName: "Knowles" }, + { firstName: "Ólafur", lastName: "Arnalds" }, + { firstName: "David", lastName: "Jones" }, + { firstName: "Zoë", lastName: "Deschanel" }, +]; + +function sortAlphabetically(arr) { + return arr.sort((a, b) => { + if (a.firstName < b.firstName) { + return -1; + } + + if (a.firstName > b.firstName) { + return 1; + } + + return 0; + }); +} + +sortAlphabetically(people); +``` + +By default, string comparison in JavaScript is not language-sensitive (meaning it doesn’t take into account language-specific rules or special characters like accents), which results in the sorted list not being in the correct order. + +The solution is to leverage `Intl.Collator` which enables language-sensitive string comparison. + +```javascript +function sortAlphabetically(arr) { + const collator = new Intl.Collator("en", { sensitivity: "base" }); + return arr.sort((a, b) => collator.compare(a.firstName, b.firstName)); +} +``` diff --git a/javascript/sort-numbers.md b/javascript/sort-numbers.md index 7091d72..36f2d3b 100644 --- a/javascript/sort-numbers.md +++ b/javascript/sort-numbers.md @@ -1,4 +1,4 @@ -# Sort array of numbers +# Sort Array of Numbers In javascript, the `Array` `sort` function will cast everything to a string. So when you have an array of numbers, you need to repetitively cast them to numbers: