.sort()

Hi guys I try sorting my array, and unfortunately I was not able to return it in a particular a-z
3 Replies
jtzuya
jtzuya2y ago
0
:
"Category_Changing Habits"
1
:
"Category_News"
2
:
"Category_Sustainability"
3
:
"Category_Waste Stream Management"
4
:
"FAQs"
5
:
"What are the benefits of recycling waste?"
6
:
"What type of waste can be recycled?"
7
:
"Which country recycles the most waste?"
8
:
"Why seperate waste?"
9
:
"compost"
10
:
"e-waste"
11
:
"recycle"
12
:
"waste"
13
:
"zerowaste"
0
:
"Category_Changing Habits"
1
:
"Category_News"
2
:
"Category_Sustainability"
3
:
"Category_Waste Stream Management"
4
:
"FAQs"
5
:
"What are the benefits of recycling waste?"
6
:
"What type of waste can be recycled?"
7
:
"Which country recycles the most waste?"
8
:
"Why seperate waste?"
9
:
"compost"
10
:
"e-waste"
11
:
"recycle"
12
:
"waste"
13
:
"zerowaste"
See my "e-waste" is placed at index 10 should be after C isn't it?
13eck
13eck2y ago
Array.sort() uses the ASCII table by default, so capital and lowercase letters are in different places Your capital letters are sorted first, followed by lowercase letters because that's the numerical sort order. Capital C, for example, is ASCII number 67 while lowercase c is ASCII number 99 What you want is case-insensitive sorting so you'll have to write your own sorting function that either changes all letters to caps or to all lowercase For example, if you pass this function as the argument to your .sort() it'll sort them alphabetically:
const compareString = (a,b) => a.toLowerCase() > b.toLowerCase() ? 1 : a.toLowerCase() < b.toLowerCase() ? -1 : 0;
const compareString = (a,b) => a.toLowerCase() > b.toLowerCase() ? 1 : a.toLowerCase() < b.toLowerCase() ? -1 : 0;
jtzuya
jtzuya2y ago
I see, that's definitely helpful thanks man