You can use sort()
to sort an array alphabetically:
const a = ['b', 'd', 'c', 'a']
a.sort() //['a', 'b', 'c', 'd']
This does not work for numbers, as it sorts for ASCII value (0-9A-Za-z
)
const a = [1, 2, 3, 10, 11]
a.sort() //1, 10, 11, 2, 3
const b = [1, 'a', 'Z', 3, 2, 11]
b.sort() //1, 11, 2, 3, Z, a
You can sort by number value using a custom function:
const a = [1, 4, 3, 2, 5]
a.sort((a, b) => (a > b ? 1 : -1)) //1, 2, 3, 4, 5
Reverse the sort order of an array using reverse()
:
a.reverse()
Lessons this unit:
0: | Introduction |
1: | map() |
2: | filter() |
3: | reduce() |
4: | ▶︎ sort() |
5: | find() and findIndex() |
6: | forEach() |