-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
new file: javascript/sort-alphabetically.md
- Loading branch information
Showing
2 changed files
with
41 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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)); | ||
} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters