Skip to content

Commit cca2d67

Browse files
committed
Coding question about sorting non-ASCII
1 parent c654abf commit cca2d67

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Diff for: README.md

+39
Original file line numberDiff line numberDiff line change
@@ -11640,6 +11640,45 @@ Even though there is a timer of 5 seconds supplied to `setTimeout` callback, it
1164011640
1164111641
**[⬆ Back to Top](#table-of-contents)**
1164211642
11643+
#### 84. What is the output of below code?
11644+
11645+
```javascript
11646+
let arr = ['wöchentlich','Woche', 'wäre', 'Wann'];
11647+
console.log(arr.sort());
11648+
```
11649+
11650+
- 1: ['wöchentlich','Woche', 'wäre', 'Wann']
11651+
- 2: ['Wann', 'wäre', 'Woche', 'wöchentlich']
11652+
- 3: ['Wann', 'Woche', 'wäre', 'wöchentlich']
11653+
- 4: ['wäre', 'Wann', 'wöchentlich','Woche']
11654+
11655+
<details><summary><b>Answer</b></summary>
11656+
<p>
11657+
11658+
##### Answer: 3
11659+
11660+
Javascript has a native method sort that allows sorting an array of elements in-place. It will treat each element as a string and sort it alphabetically. But if you try to sort an array of strings which has non-ASCII characters, you will receive a strange result. This is because characters with an accent have higher character codes.
11661+
11662+
In this case, the sort order of an array is ['Wann', 'Woche', 'wäre', 'wöchentlich'].
11663+
11664+
If you want to sort an array of string values which has non-ASCII characters in an ascending order, there are two possible options like **localeCompare** and **Intl.Collator** provided by ECMAScript Internationalization API.
11665+
11666+
**localeCompare:**
11667+
```javascript
11668+
let arr = ['wöchentlich','Woche', 'wäre', 'Wann'];
11669+
console.log(arr.sort((a, b) => a.localeCompare(b))); //['Wann', 'wäre', 'Woche', 'wöchentlich']
11670+
```
11671+
**Intl.Collator:**
11672+
```javascript
11673+
let arr = ['wöchentlich','Woche', 'wäre', 'Wann'];
11674+
console.log(arr.sort(Intl.Collator().compare)); //['Wann', 'wäre', 'Woche', 'wöchentlich']
11675+
```
11676+
11677+
</p>
11678+
</details>
11679+
11680+
**[⬆ Back to Top](#table-of-contents)**
11681+
1164311682
## Disclaimer
1164411683
1164511684
The questions provided in this repository are the summary of frequently asked questions across numerous companies. We cannot guarantee that these questions will actually be asked during your interview process, nor should you focus on memorizing all of them. The primary purpose is for you to get a sense of what some companies might ask — do not get discouraged if you don't know the answer to all of them ⁠— that is ok!

0 commit comments

Comments
 (0)