Skip to content

Commit

Permalink
new file: javascript/sort-alphabetically.md
Browse files Browse the repository at this point in the history
  • Loading branch information
byt3h3ad committed Oct 18, 2023
1 parent eb3664c commit 706d87d
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
40 changes: 40 additions & 0 deletions javascript/sort-alphabetically.md
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));
}
```
2 changes: 1 addition & 1 deletion javascript/sort-numbers.md
Original file line number Diff line number Diff line change
@@ -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:

Expand Down

0 comments on commit 706d87d

Please sign in to comment.